c++c++11stlinitializer-list

Compare STL container contents to an initialiser list


I want to do something like

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

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

is this possible?


Solution

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

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

    expected result:

    same? : 1