Compare STL容器内容到initialiserlist

问题描述 投票:0回答:4
std::vector<int> foobar() { // Do some calculations and return a vector } std::vector<int> a = foobar(); ASSERT(a == {1, 2, 3});

这是可能的吗?

不幸的是,您不能超载
operator==

接受第二个参数(这是语言规则)。

,但是您可以定义任何其他函数以将const引用到
c++ c++11 stl initializer-list
4个回答
5
投票

initializer_list
预期结果:

#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; }

    

YYES:
same? : 1

您已经明确指定右手操作数的类型。例如

3
投票

由于

std::vector<int> v = { 1, 2, 3 }; assert( v == std::vector<int>( { 1, 2, 3 } ) );
是模板功能,并且编译器无法将第二操作数推导为类型
operator ==

2
投票

我知道的最自然和/或“最漂亮”的工作实现,假设您想做的事情是不可能的(正如本网站上的人们多次所说的那样),是
std::vector<int>

您的

typedef
类型如下:
vector


2
投票
如果有人知道一些更自然的东西,请让我们知道。


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.