将STL容器内容与初始化程序列表进行比较
Compare STL container contents to an initialiser list
我想做一些类似的事情
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
:的常量引用
#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
是:
ASSERT(a == std::vector<int>{1,2,3});
您必须明确指定右手操作数的类型。例如
std::vector<int> v = { 1, 2, 3 };
assert( v == std::vector<int>( { 1, 2, 3 } ) );
因为operator ==
是一个模板函数,编译器无法将第二个操作数推导为类型std::vector<int>
据我所知,假设你想做的事情是不可能的(正如本网站上的人多次所说),最自然和/或"最漂亮"的工作实现是typedef
,你的vector
类型如下:
typedef std::vector<int> vec;
ASSERT(a == vec({1, 2, 3}));
其中vec
是根据您的需要命名的。
如果有人知道一些更自然的东西,请告诉我们。
相关文章:
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 处理程序的模块列表中有一个错误的模块"WebSocketModule"
- 程序输入名称和高度并显示它。我不知道如何显示列表中最高人的姓名和身高
- 如何在C / C++中正确实现链接列表而不会使程序崩溃
- 在C++初始化程序列表中使用Integer Literals
- 如何实现否定用户输入退出程序和打印列表?
- C++ Win32 列表框和滑块创建 Windows 应用程序
- C 需要帮助的作业程序,该程序在文件列表中读取并在每个双重的双重列表中添加一个字符串
- 将数组/对象/结构列表从C#库中传递给C MFC应用程序
- 如何制作一个结构程序,在其中可以存储无限量的数据,以便每次您想要时都可以将另一个产品添加到列表中?
- 内部源代码 - 在链接列表实现中插入元素上的删除会破坏整个应用程序
- 简单链接列表程序中的Destructor segfault
- C 链接的列表用户输入限制验证导致程序结束
- 我的链接列表程序在代码块编译器(X0000000005)中以状态-1073741819终止
- 初始值设定项列表程序运行良好,但直接赋值时无法正常工作
- 如何使用类将歌曲添加到播放列表程序中
- 使用C++列表标准库来帮助链接列表程序
- 变量参数列表程序行为异常-csdarg
- 当我调用一个函数时,c++列表程序冻结
- 目录列表程序出错,c++