Possible Duplicate:
C++: Easiest way to initialize an STL vector with hardcoded elements
How to initialize a vector in c++
I was wondering if there's a way to make a vector with announced elements..
Instead of having to do:
vector< int > v;
v.push_back(3);
v.push_back(5);
v.push_back(1);
and etc, where v = {3,5,1}
,
I want to make a vector that already contains elements like:
vector< int > v = {3,5,1};
Because it is a lot of work inserting each number in the vector. Is there a shortcut to this?
Yes, but sorting a vector modifies the original content.
Yes, std::vector<T>::push_back() creates a copy of the argument and stores it in the vector.
Copy enables you to: define a vector of operands, copy the values or bit status of each operand within that vector, write those values or status into a corresponding vector of operands of the same length.
C++11 supports exactly the syntax you suggest:
vector< int > v = {3,5,1};
This feature is called uniform initialization.
There isn't any "nice" way to do this in previous versions of the language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With