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?
Try pass array to vector: int arr[] = {2,5,8,11,14}; std::vector<int> TestVector(arr, arr+5); You could always call std::vector::assign to assign array to vector, call std::vector::insert to add multiple arrays.
Sum up of all elements of a C++ vector can be very easily done by std::accumulate method. It is defined in <numeric> header. It accumulates all the values present specified in the vector to the specified sum.
Yes it is possible to hold two different types, you can create a vector of union types. The space used will be the larger of the types.
c (vector,operation (iterator) ) is an append function which will append values to the vector by performing some operation Here we are going to append a value for an existing vector. Here we are going to append multiple values to the existing vector using for loop. for (iterator in range) { vector = c (existing_vector, iterator) }
How to append a single value, a series, or another vector at the beginning, end or at any desired position in a given vector. append () function is used to add elements to a given vector. This function takes atleast two arguments and atmost three arguments. Lets see the syntax 1. append () is the function which will add elements to a vector.
If a value or a vector is to be added in a given vector at a specific location then the third argument "after" is used. It is simply the subscript after which values are to be added. If you want to add after the first value in list, use 1 as argument, if you want to add after the second value, use 2 as argument and so on.
append () function is used to add elements to a given vector. This function takes atleast two arguments and atmost three arguments. Lets see the syntax 1. append () is the function which will add elements to a vector. 2. vector is the first argument. It is the vector in which values are going to be added. This argument is necessary.
This should work:
std::vector<int> values;
values.insert( values.end(), { 1, 2, 3, 4 } );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With