简体   繁体   中英

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?

Something like this:

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

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

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

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

会做的事情。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM