Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: How to make a vector that already contains elements [duplicate]

Tags:

c++

vector

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?

like image 950
user1284619 Avatar asked Mar 21 '12 23:03

user1284619


People also ask

Are duplicates allowed in vector?

Yes, but sorting a vector modifies the original content.

Does Push_back make a copy?

Yes, std::vector<T>::push_back() creates a copy of the argument and stores it in the vector.

What is a vector copy?

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.


1 Answers

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.

like image 53
Greg Hewgill Avatar answered Sep 22 '22 22:09

Greg Hewgill