我正在开发一个用于构建记录的类(具有固定数量的字段)。我的公共方法允许用户按索引插入单个值。没有要求用户填写所有字段 - 所以我想将表示记录的向量预分配为确切的大小,每个字段都初始化为空字符串。
有没有办法比推回循环更容易做到这一点?
我正在开发一个用于构建记录的类(具有固定数量的字段)。我的公共方法允许用户按索引插入单个值。没有要求用户填写所有字段 - 所以我想将表示记录的向量预分配为确切的大小,每个字段都初始化为空字符串。
有没有办法比推回循环更容易做到这一点?
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);
会做的事情。