简体   繁体   中英

Add multiple values to a vector

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?

This should work:

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

Perhaps with insert :

values.insert( values.end(),  {3, 9, 2, 5, 8, etc} );

Demo .

In order to present as much as possible solutions, this should work too:

for(const auto x : {11, 12, 13, 14})
    v.push_back(x);

Demo .

You can just make an operator:

template <class T>
std::vector<T>& operator+=(std::vector<T>& lhs, std::initializer_list<T> l)
{
    lhs.insert(std::end(lhs), l);
    return lhs;
}

You can mimic the boost boost::assign behavior

template <typename T> 
class vector_adder 
{
public:
    std::vector<T>& v;
    vector_adder(std::vector<T>& v):v(v)
    {  }

    vector_adder& operator,(const T& val)
    {  
       v.push_back(val);
       return *this;
    }
};

template <typename T> 
vector_adder<T> operator+=(std::vector<T>& v,const T& x)
{
    return vector_adder<T>(v),x;
}

Then,

 std::vector<int> v {1,2,3,4};
 v += 11,12,13,14 ;

See here

You can do it by using the insert member function, as such:

vector<int> v; 
int myarr[] {1, 2, 4, 5, 5, 6, 6, 8}; //brace initialization with c++11

v.insert(v.end(), myarr, myarr+8);

There was a previous answer that omitted the middle argument in the insert parameters, but that one does not work. There are several formats to follow for the insert method, which can be found here and the code snippet I wrote practically follows this format:

vectorName.insert(postion to start entering values, first value to enter, how many values to enter)

Note: That the last two arguments (ie myarr, myarr+8) use pointer arithmetics. myarr is the address in memory of the first element in the array, and the second value is the address of the 8th element. You can read about pointer arithmetic here .

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM