How to initialize a vector in C++

687,066

Solution 1

With the new C++ standard (may need special flags to be enabled on your compiler) you can simply do:

std::vector<int> v { 34,23 };
// or
// std::vector<int> v = { 34,23 };

Or even:

std::vector<int> v(2);
v = { 34,23 };

On compilers that don't support this feature (initializer lists) yet you can emulate this with an array:

int vv[2] = { 12,43 };
std::vector<int> v(&vv[0], &vv[0]+2);

Or, for the case of assignment to an existing vector:

int vv[2] = { 12,43 };
v.assign(&vv[0], &vv[0]+2);

Like James Kanze suggested, it's more robust to have functions that give you the beginning and end of an array:

template <typename T, size_t N>
T* begin(T(&arr)[N]) { return &arr[0]; }
template <typename T, size_t N>
T* end(T(&arr)[N]) { return &arr[0]+N; }

And then you can do this without having to repeat the size all over:

int vv[] = { 12,43 };
std::vector<int> v(begin(vv), end(vv));

Solution 2

You can also do like this:

template <typename T>
class make_vector {
public:
  typedef make_vector<T> my_type;
  my_type& operator<< (const T& val) {
    data_.push_back(val);
    return *this;
  }
  operator std::vector<T>() const {
    return data_;
  }
private:
  std::vector<T> data_;
};

And use it like this:

std::vector<int> v = make_vector<int>() << 1 << 2 << 3;
Share:
687,066

Related videos on Youtube

Md Faisal
Author by

Md Faisal

Application Developer 2 at Oracle

Updated on January 31, 2020

Comments

  • Md Faisal
    Md Faisal over 4 years

    I want to initialize a vector like we do in case of an array.

    Example

    int vv[2] = {12, 43};
    

    But when I do it like this,

    vector<int> v(2) = {34, 23};
    

    OR

    vector<int> v(2);
    v = {0, 9};
    

    it gives an error:

    expected primary-expression before ‘{’ token

    AND

    error: expected ‘,’ or ‘;’ before ‘=’ token

    respectively.

    • Shadow2531
      Shadow2531 over 12 years
    • Admin
      Admin about 11 years
      You should enable C++11 support in your compiler, e.g. g++ -std=c++11 your_file.cc. Then you can use initializer list constructor of the thread (the last item in this reference)
    • Martin Beckett
      Martin Beckett about 11 years
      Not a dupe - the other question is how to do it with old c++, WTF's answer is how to do it now
  • Violet Giraffe
    Violet Giraffe over 12 years
    Or simply: std::vector<int> v(vv, vv+2);
  • James Kanze
    James Kanze over 12 years
    Or more robustly: std::vector<int> v(begin(w), end(w);. The begin and end are standard in C++11 (but then you don't need them), but should be in your tool kit otherwise.
  • Mortimer McMire
    Mortimer McMire about 11 years
    I know this is an old question, but what exactly are you doing here: std::vector<int> v(&vv[0], &vv[0]+2); ? What I see is, you're constructing a vector with room for &vv[0] (which will be a memory address) values, and filling each space in the vector with &vv[0]+2... That would be using constructor 2 on this page: en.cppreference.com/w/cpp/container/vector/vector without supplying the third argument, which defaults to Allocator(). I know I'm missing something.
  • Prashant Kumar
    Prashant Kumar about 11 years
    I think std::vector<int> v(&vv[0], &vv[0]+2) is invoking the 4th constructor on that page, actually. The constructor can take the first and last element in a range and create a vector with everything in between. The tipoff is the & will result in memory addresses.
  • qed
    qed almost 10 years
    What if I want to initialize an array on the heap?
  • R. Martinho Fernandes
    R. Martinho Fernandes almost 10 years
    @qed what do you think vector is?
  • qed
    qed almost 10 years
    I don't know, a data container?
  • R. Martinho Fernandes
    R. Martinho Fernandes almost 10 years
    And what's an array if not a data container, too?
  • R. Martinho Fernandes
    R. Martinho Fernandes almost 10 years
    @qed A vector is an array on the heap.
  • qed
    qed almost 10 years
    @R.MartinhoFernandes Cool. But how come we never delete a vector by hand?
  • qed
    qed almost 10 years
    @R.MartinhoFernandes And if I do vector<int> b {1, 2}, is b then a pointer to a vector on the heap? Is that different from vector<int>* b = new vector<int>; b.push_back(1); b.push_back(2)?
  • Buge
    Buge almost 10 years
    @qed We never delete vectors by hand because they have a destructor that automatically deletes the stuff on the heap, and the destructor is automatically called when the vector goes out of scope.
  • Buge
    Buge almost 10 years
    @qed Your second example has a bug. I think you mean b->push_back(1);. In the first example b is not a pointer, it is a object. The difference between those two examples is where the metadata (size and address of the main data) is stored. In the first example the size and address of the main data are stored on the stack. In the second example the size and address of the main data are stored on the heap. In both cases the main data itself is stored on the heap.
  • Tik0
    Tik0 almost 7 years
    Which standard do you mean by new
  • Per
    Per over 6 years
    Is it possible to move data_ to v instead of calling the copy constructor?
  • Viktor Sehr
    Viktor Sehr over 6 years
    Hello Per! I suppose you do like this (warning, untested): operator std::vector<T>&& () { return std::move(data_); }