将STL容器内容与初始化程序列表进行比较

Compare STL container contents to an initialiser list

本文关键字:列表 程序 比较 STL 初始化      更新时间:2023-10-16

我想做一些类似的事情

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是根据您的需要命名的。

如果有人知道一些更自然的东西,请告诉我们。