9

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?

1

5 Answers 5

13

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.

1
4

You can use boost::assign

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

You can do in C++11

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

as Greg Hewgill suggessted or in C++98

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

compliments to: https://stackoverflow.com/a/2236227/1276982

2

Yes in C++11 you can do

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

you can create multiple elements of the same value through the 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 sort 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

C++11 has such a feature, most compilers support it.

To enable in gcc:

    g++ -std=gnu++0x

VS2010 supports it out of the box I think

Not the answer you're looking for? Browse other questions tagged or ask your own question.