我想做类似的事情
std::vector<int> foobar()
{
// Do some calculations and return a vector
}
std::vector<int> a = foobar();
ASSERT(a == {1, 2, 3});
这可能吗?
最佳答案
不幸的是,您不能重载 operator==
来接受 std::initializer_list
作为第二个参数(这是语言规则)。
但是您可以定义任何其他函数来获取对 initializer_list
的 const 引用:
#include <iostream>
#include <algorithm>
#include <vector>
template<class Container1, typename Element = typename Container1::value_type>
bool equivalent(const Container1& c1, const std::initializer_list<Element>& c2)
{
auto ipair = std::mismatch(begin(c1),
end(c1),
begin(c2),
end(c2));
return ipair.first == end(c1);
}
int main() {
std::vector<int> x { 0, 1, 2 };
std::cout << "same? : " << equivalent(x, { 0 , 1 , 2 }) << std::endl;
}
预期结果:
same? : 1
关于c++ - 将 STL 容器内容与初始化列表进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33781070/