99

Currently when I have to use vector.push_back() multiple times.

The code I'm currently using is

std::vector<int> TestVector;
TestVector.push_back(2);
TestVector.push_back(5);
TestVector.push_back(8);
TestVector.push_back(11);
TestVector.push_back(14);

Is there a way to only use vector.push_back() once and just pass multiple values into the vector?

Yun
  • 3,056
  • 6
  • 9
  • 28
Elliott
  • 1,347
  • 4
  • 17
  • 23
  • 1
    possible duplicate of [How do you copy the contents of an array to a std::vector in C++ without looping?](http://stackoverflow.com/questions/259297/how-do-you-copy-the-contents-of-an-array-to-a-stdvector-in-c-without-looping) – sashoalm Jan 28 '13 at 12:29

8 Answers8

150

You can do it with initializer list:

std::vector<unsigned int> array;

// First argument is an iterator to the element BEFORE which you will insert:
// In this case, you will insert before the end() iterator, which means appending value
// at the end of the vector.
array.insert(array.end(), { 1, 2, 3, 4, 5, 6 });
Kosiek
  • 1,659
  • 1
  • 10
  • 11
  • 13
    I prefer this answer to the accepted one since it does work on non-empty vectors. – YSC Sep 22 '17 at 10:02
  • 2
    I prefer this answer to the accepted one because it is a one-liner, which fits because it is a trivial use case – IceFire Oct 05 '18 at 09:04
  • 2
    I prefer this answer because it is not restricted to initialization only. I was looking for a solution to add multiple new elements after the vector was initialized and containing data. – Martí Jul 14 '21 at 10:43
  • I'm getting an error adding the scalar: src//main.cpp:11:30: error: expected expression stack1.insert(stack1.end(), {2, 4, 6, 8, 1, 3, 5, 7, 9}); do you know why this could be? – DrSocket Apr 22 '22 at 13:16
  • A fine answer, although naming a vector "array" is not ideal. – Yun Jul 10 '23 at 10:03
79

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.

If you use C++11, you can try:

std::vector<int> v{2,5,8,11,14};

Or

std::vector<int> v = {2,5,8,11,14};
Yun
  • 3,056
  • 6
  • 9
  • 28
billz
  • 44,644
  • 9
  • 83
  • 100
  • 1
    the other two methods need enabled with C++11, if you use g++, compile it with `g++ -std=c++11` – billz Jan 28 '13 at 12:33
  • 15
    But what if you need to pass multiple values *after* initialization. How would we do that without a lot of push_back calls? – David G Jan 28 '13 at 12:34
  • But this will clear the previous contents. OP wants an equivalent of multiple push operations. I think the solution would then be to use a back inserter / vector::insert. – leemes Jan 28 '13 at 12:37
  • 1
    @David you can use `std::vector::insert` – juanchopanza Jan 28 '13 at 12:39
78

You can also use vector::insert.

std::vector<int> v;
int a[5] = {2, 5, 8, 11, 14};

v.insert(v.end(), a, a+5);

Edit:

Of course, in real-world programming you should use:

v.insert(v.end(), a, a+(sizeof(a)/sizeof(a[0])));  // C++03
v.insert(v.end(), std::begin(a), std::end(a));     // C++11
Chris Nolet
  • 8,714
  • 7
  • 67
  • 92
sashoalm
  • 75,001
  • 122
  • 434
  • 781
  • 11
    In C++11, there is the better solution `std::end(a)` available. – leemes Jan 28 '13 at 12:39
  • 1
    Thanks, I didn't know about it. Perhaps you can add it as a new answer? – sashoalm Jan 28 '13 at 13:07
  • That's a too small change worth a new answer. Let's just keep this as a comment (or you can edit your answer). – leemes Jan 28 '13 at 13:10
  • 1
    a+5 not good. Use a+(sizeof(a)/sizeof(int)) . No need to update that statement every time you add elements to "a". – deepdive Oct 16 '13 at 14:12
  • @DivyangPatel, and even better is to use a+(sizeof(a)/sizeof(*a)), which works for any array type (thus safer to copy-paste). – Steed Oct 25 '13 at 13:25
  • @DivyangPatel I know that :) But I like to keep example code short n' simple. Those who read it should know better than to to copy it verbatim. Frankly, `a+(sizeof(a)/sizeof(int))` looks clunky. – sashoalm Dec 13 '13 at 07:45
  • @sashoalm Your argument is valid. But mine was addition for real-life programming... :):) – deepdive Dec 16 '13 at 08:22
5

These are the three most straight forward methods:

1) Initialize from an initializer list:

std::vector<int> TestVector = {2,5,8,11,14};

2) Assign from an initializer list:

std::vector<int> TestVector;
TestVector.assign( {2,5,8,11,14} ); // overwrites TestVector

3) Insert an initializer list at a given point:

std::vector<int> TestVector;
...
TestVector.insert(end(TestVector), {2,5,8,11,14} ); // preserves previous elements
alfC
  • 14,261
  • 4
  • 67
  • 118
4

You can also use Boost.Assignment:

const list<int> primes = list_of(2)(3)(5)(7)(11);

vector<int> v; 
v += 1,2,3,4,5,6,7,8,9;
zxxc
  • 355
  • 3
  • 12
2

Since c++17 you could use the following method:

#include <iostream>
#include <vector>

using namespace std;

vector<int> vec;
template<typename... T>
void vecPush(const T& ... x) {
    (vec.push_back(x), ...);
}

int main() {
    vecPush(4, 10, 4);
    for(const auto& a : vec)
        cout << a << " ";
    return 0;
}
1

These days (c++17) it's easy:

auto const pusher([](auto& v) noexcept
  {
    return [&](auto&& ...e)
      {
        (
          (
            v.push_back(std::forward<decltype(e)>(e))
          ),
          ...
        );
      };
  }
);

pusher(TestVector)(2, 5, 8, 11, 14);

EDIT: for the really adventurous (c++20):

template <typename F, class Tuple>
constexpr void operator|(Tuple&& t, F f)
{
  [&]<auto ...I>(std::index_sequence<I...>) noexcept(noexcept((f(std::get<I>(t)), ...)))
  {
    (f(std::get<I>(t)), ...);
  }
  (std::make_index_sequence<std::tuple_size_v<std::remove_reference_t<Tuple>>>());
}

std::forward_as_tuple(2, 5, 8, 11, 14) | [&](auto&& e){ TestVector.push_back(std::forward<decltype(e)>(e)); }
user1095108
  • 14,119
  • 9
  • 58
  • 116
-3

Yes you can, in your case:

vector<int>TestVector;`
for(int i=0;i<5;i++)
{

    TestVector.push_back(2+3*i);
    
} 
HackSlash
  • 4,944
  • 2
  • 18
  • 44
  • 4
    This solution avoids duplicating code, but the function push_back still gets called multiple times, probably not what the question asker wanted. (Code formatting is off, too.) – Viktoriya Malyasova Feb 22 '21 at 17:25
  • Ok he asked for using push_back for once but its functionality must be multiple i think – Probol Feb 23 '21 at 18:20