Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

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

I can build an array and initialize it similar this:
int a[] = {10, 20, 30};

Whereby do I perform a std::vector and initialize it likewise elegant?

The most reliable approach I remember is:
std::vector<int> ints;

ints.push_back(10);
ints.push_back(20);
ints.push_back(30);


Is there a more reliable method?
by

2 Answers

akshay1995
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]) );
kshitijrana14
typedef std::vector<int> arr;
arr a {10, 20, 30}; // This would be how you initialize while defining

To compile use:
clang++ -std=c++11 -stdlib=libc++  <filename.cpp>

Login / Signup to Answer the Question.