Add multiple values to a vector

Eejin picture Eejin · Nov 11, 2014 · Viewed 22.3k times · Source

I have a vector of ints that I want to add multiple values too but too many values to add using a lot of push_backs. Is there any method of adding multiple values at the end of a vector. Something along the lines of this:

std::vector<int> values
values += {3, 9, 2, 5, 8, etc};

I found that boost has something like this, but I would like not having to include boost.

#include <boost/assign/std/vector.hpp>

using namespace boost::assign;

{
    std::vector<int> myElements;
    myElements += 1,2,3,4,5;
}

Which seems to be declared like this:

template <class V, class A, class V2>
inline list_inserter<assign_detail::call_push_back<std::vector<V,A> >, V> 
operator+=( std::vector<V, A>& c, V2 v )
{
    return push_back( c )( v );
}

Is there any C++/C++11 way to do this or, if not, how would it be implemented?

Answer

Slava picture Slava · Nov 11, 2014

This should work:

std::vector<int> values;
values.insert( values.end(), { 1, 2, 3, 4 } );