Chap
Chap

Reputation: 3835

C++ instantiating std::vector<std::string> with fixed number of empty strings

I'm developing a class for building records (with a fixed number of fields). My public methods allow the user to insert individual values by index. There's no requirement that the user fill in all fields -- so I'd like to preallocate the vector that represents the record to the exact size, with every field initialized to the empty string.

Is there a way to do this more easily than with a push-back loop?

Upvotes: 4

Views: 11954

Answers (3)

4pie0
4pie0

Reputation: 29724

std::vector<std::string> v(N);

will do the thing.

Upvotes: 0

Antonio
Antonio

Reputation: 20286

You just have to choose one of the standard constructor of the vector class, that is the one that receives in input the number of elements (generated with the default constructor, it would be an empty string for std::string) you want to put in your vector from the beginning.

int N = 10;
std::vector<std::string> myStrings(N);

You can also initialize all your strings to a different value that an empty string, for example:

int N = 10;
std::vector<std::string> myStrings(N,std::string("UNINITIALIZED") );

Documentation: http://www.cplusplus.com/reference/vector/vector/vector/

You might also be interested to read this: Initializing an object to all zeroes

Upvotes: 2

juanchopanza
juanchopanza

Reputation: 227438

Something like this:

std::vector<std::string> v(N);

where N is the number of strings. This creates a vector with N empty strings.

Upvotes: 13

Related Questions