Antonello
Antonello

Reputation: 6431

How to initialise in C++11 in one line a vector of n equal elements?

I know in C++11 I can construct a vector with a syntax like:

vector <int> a = {1,2,3,4,5};

but is it possible without looping in a similar way to initialise the vector for a number of equal elements ?

e.g.

int n= 5;
vector <string> a = (n, {"bbb"});

Upvotes: 0

Views: 147

Answers (3)

Antonello
Antonello

Reputation: 6431

I looked everywhere in s.o. and then the answer was just in the c++ ref: http://www.cplusplus.com/reference/vector/vector/vector/

It should be as simply as:

int n= 5;
vector<string> a (n,"bbb");

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254431

You're almost there. There's a constructor to specify the size and (optionally) a value to initialise the elements with:

vector<string> a(n, "bbb");

Upvotes: 5

juanchopanza
juanchopanza

Reputation: 227390

Yes,

vector<string> a(n, "bbb");

This works in C++03 too.

Upvotes: 7

Related Questions