patterncppCritical
What is the easiest way to initialize a std::vector with hardcoded elements?
Viewed 0 times
witheasiestinitializehardcodedthestdvectorwaywhatelements
Problem
I can create an array and initialize it like this:
How do I create a
The best way I know is:
Is there a better way?
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 ints;
ints.push_back(10);
ints.push_back(20);
ints.push_back(30);Is there a better way?
Solution
One method would be to use the array to initialize the vector
static const int arr[] = {16,2,77,29};
vector vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );Code Snippets
static const int arr[] = {16,2,77,29};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );Context
Stack Overflow Q#2236197, score: 591
Revisions (0)
No revisions yet.