user1899020 user1899020 -4 years ago 85
C++ Question

How to compare a container and a initializer-list to see if they are equal?

For example

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


And check by

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


But error in my code. No conversion from list to container. How to fix the bug?

Answer Source

Your example, as currently written, will not only fail to compile because of the comparison, but also because the template parameter List cannot be deduced from a braced-init-list.

Either change the function to

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

or change the way you call it

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});

To fix the comparison, as Igor mentions in the comments, use

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

Or, if you have access to the C++14 overload of std::equal that takes begin and end iterators to both ranges, you can skip the size check

return std::equal(std::begin(c), std::end(c), std::begin(l), std::end(l));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download