2017-03-01 24 views
0

例如如何比较容器和初始化程序列表以查看它们是否相等?

template<class Container, class List> 
bool isEqual(Container const& c, List const& l) 
{ 
    return c == Container(l); // Error!! 
} 

并检查通过

std::vector<int> v; 
bool b = isEqual(v, {1, 2, 3}); 

但错误在我的代码。没有从列表转换到容器。如何解决这个错误?

+2

'返回c.size()== l.size()&&的std ::相等(std :: begin(c),std :: end(c),std :: begin(l));' –

+1

比较不是你的例子唯一的问题,'List'不能从braced-初始化列表 – Praetorian

回答

3

你举的例子,按照目前的写,不仅会失败,因为比较的编译,而且因为模板参数Listcannot be deduced支撑,初始化列表

要么改变的功能

template<class Container, class T> 
bool isEqual(Container const& c, std::initializer_list<T> const& l) 

或更改你怎么称呼它

std::vector<int> v; 
auto l = {1, 2, 3}; 
bool b = isEqual(v, l); 
// or 
bool b = isEqual(v, std::initializer_list<int>{1, 2, 3}); 

要解决的比较,因为伊戈尔在评论中提到的方法,使用

return c.size() == l.size() && std::equal(std::begin(c), std::end(c), std::begin(l)); 

或者,如果您有权限s到的std::equal的C++ 14重载采用开始和结束迭代器两个范围,则可以跳过该大小检查

return std::equal(std::begin(c), std::end(c), std::begin(l), std::end(l)); 
相关问题