C++实例化 std::vector<std::string> 具有固定数量的空字符串

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

本文关键字:std 字符串 gt vector 实例化 lt string C++      更新时间:2023-10-16

我正在开发一个用于构建记录的类(具有固定数量的字段)。我的公共方法允许用户通过索引插入单个值。不需要用户填写所有字段,所以我想将表示记录的向量预先分配到确切的大小,每个字段都初始化为空字符串。

有没有比回推环更容易做到这一点的方法?

类似这样的东西:

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

其中CCD_ 1是字符串的数目。这将创建一个具有N空字符串的向量。

您只需选择向量类的一个标准构造函数,即从一开始就接收要放入向量中的元素数量(使用默认构造函数生成,对于std::string来说,它将是一个空字符串)的构造函数。

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

您还可以将所有字符串初始化为与空字符串不同的值,例如:

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

文件:http://www.cplusplus.com/reference/vector/vector/vector/

您可能也有兴趣阅读以下内容:将对象初始化为全零

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

会做这件事。