将STL容器内容与初始化列表进行比较 [英] Compare STL container contents to an initialiser list

查看:114
本文介绍了将STL容器内容与初始化列表进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做像

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

std::vector<int> a = foobar();
ASSERT(a == {1, 2, 3});

这是否可能?

推荐答案

不幸的是,您不能重载运算符== 接受 std :: initializer_list 第二个参数(这是一个语言规则)。

Unfortunately you cannot overload operator== to accept a std::initializer_list as the second argument (this is a language rule).

但是你可以定义任何其他的函数来引用 initializer_list

But you can define any other function to take a const reference to an 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

这篇关于将STL容器内容与初始化列表进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆