C ++: how to create a vector that already contains elements

Possible duplicate:
C ++: The easiest way to initialize an STL vector with hard-coded elements
How to initialize a vector in C ++

I was wondering if there is a way to make a vector with declared elements.

Instead of doing:

vector< int > v; v.push_back(3); v.push_back(5); v.push_back(1); 

etc., where v = {3,5,1},

I want to create a vector that already contains elements such as:

 vector< int > v = {3,5,1}; 

Because a lot of work inserts each number into a vector. Is there a shortcut for this?

+6
source share
5 answers

C ++ 11 supports exactly the syntax you suggest:

 vector< int > v = {3,5,1}; 

This function is called uniform initialization .

In previous versions of the language, there is no β€œpleasant” way.

+11
source

You can use boost::assign

 std::vector<int> v = boost::assign::list_of(3)(5)(1); 
+3
source

You can do in C ++ 11

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

as suggested by Greg Huglill or in C ++ 98

 static const int v_[] = {3,5,1}; std::vector<int> vec (v_, v_ + sizeof(v_) / sizeof(v_[0]) ); 

congratulations: fooobar.com/questions/15725 / ...

+2
source

Yes in C ++ 11 you can do

std :: vector v {1,2,3,4};

you can create multiple elements of the same value via constructor in C ++ 98

 std::vector<int> v (5, 6); //6 6 6 6 6 

if you don't have C ++ 11, you can create some kind of push back object

 #include <vector> struct pb{ std::vector<int>& v_; pb(std::vector<int>& v) : v_(v){}; pb& operator+(int i) { v_.push_back(i); return *this; } }; int main() { std::vector<int> d; pb(d)+4+3; } 
+1
source

C ++ 11 has such a function; most compilers support it.

To enable in gcc:

g ++ -std = gnu ++ 0x

VS2010 supports it out of the box, I think

0
source

Source: https://habr.com/ru/post/911367/


All Articles