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

dsh*_*erd 1 c++ stl c++11

我想做点什么

std::vector<int> foobar()
{
    // Do some calculations and return a vector
}

std::vector<int> a = foobar();
ASSERT(a == {1, 2, 3});
Run Code Online (Sandbox Code Playgroud)

这可能吗?

Ric*_*ges 5

不幸的是,你不能重载operator==接受a std::initializer_list作为第二个参数(这是一个语言规则).

但是你可以定义任何其他函数来获取const引用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;
}
Run Code Online (Sandbox Code Playgroud)

预期结果:

same? : 1
Run Code Online (Sandbox Code Playgroud)