c++ - 将 STL 容器内容与初始化列表进行比较

标签 c++ c++11 stl

我想做类似的事情

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/

相关文章:

c++ - native C++ 中的并行同步迭代任务

c++ - 如何将 C++ time_t 对象设置为纪元?

c++ - 在 QHBoxLayout 中将小部件添加到屏幕外以便稍后显示

c++ - 简单的 C++ vector 用法

c++ - 如何在 Visual Studio 中禁用 Microsoft 对 tchar.h 的修饰?

c++ - 我们是否仍然需要单独定义静态成员,即使它们是在类定义中初始化的?

c++ - 错误 C3861 : 'strcpy_y' : identifier not found

c++ - std::map 的反向迭代器上的 "operator-"不匹配

c++ - ostream_iterator 将数字数据写入文件的性能?

C++ glfw macosx dim screen vs f1 收藏