4

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?

1
  • 4
    Read the documentation of std::vector and look for constructors! Commented Jul 20, 2013 at 20:24

3 Answers 3

13

Something like this:

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

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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

will do the thing.

1 Comment

In which way your second version is more efficient that your first version?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.