How to initialize a vector in C++ [duplicate] How to initialize a vector in C++ [duplicate] arrays arrays

How to initialize a vector in C++ [duplicate]


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));


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;