Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to initialize a std::vector with hardcoded elements?

I can create an array and initialize it like this:

int a[] = {10, 20, 30}; 

How do I create a std::vector and initialize it similarly elegant?

The best way I know is:

std::vector<int> ints;  ints.push_back(10); ints.push_back(20); ints.push_back(30); 

Is there a better way?

like image 478
Agnel Kurian Avatar asked Feb 10 '10 10:02

Agnel Kurian


People also ask

What is the correct way to initialize vector?

Begin Declare v of vector type. Call push_back() function to insert values into vector v. Print “Vector elements:”. for (int a : v) print all the elements of variable a.

Can you initialize a vector?

How to Initialize a Vector Using a Constructor in C++ We can also initialize vectors in constructors. We can make the values to be a bit dynamic. This way, we don't have to hardcode the vector's items.


2 Answers

If your compiler supports C++11, you can simply do:

std::vector<int> v = {1, 2, 3, 4}; 

This is available in GCC as of version 4.4. Unfortunately, VC++ 2010 seems to be lagging behind in this respect.

Alternatively, the Boost.Assign library uses non-macro magic to allow the following:

#include <boost/assign/list_of.hpp> ... std::vector<int> v = boost::assign::list_of(1)(2)(3)(4); 

Or:

#include <boost/assign/std/vector.hpp> using namespace boost::assign; ... std::vector<int> v; v += 1, 2, 3, 4; 

But keep in mind that this has some overhead (basically, list_of constructs a std::deque under the hood) so for performance-critical code you'd be better off doing as Yacoby says.

like image 133
Manuel Avatar answered Sep 23 '22 18:09

Manuel


One method would be to use the array to initialize the vector

static const int arr[] = {16,2,77,29}; vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) ); 
like image 32
Yacoby Avatar answered Sep 22 '22 18:09

Yacoby