C++实例化 std::vector<std::string> 具有固定数量的空字符串
C++ instantiating std::vector<std::string> with fixed number of empty strings
我正在开发一个用于构建记录的类(具有固定数量的字段)。我的公共方法允许用户通过索引插入单个值。不需要用户填写所有字段,所以我想将表示记录的向量预先分配到确切的大小,每个字段都初始化为空字符串。
有没有比回推环更容易做到这一点的方法?
类似这样的东西:
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);
会做这件事。
相关文章:
- 我可以重新分配/覆盖std::字符串吗
- 如何将这个std::字符串转换为std::基本字符串
- std::字符串与 PCWSTR 的对话
- 重载 std::字符串运算符+ 用于打印枚举名称
- 从std::字符串创建OssBitString
- std::字符串擦除以删除最后一个字母
- 如何使用 C++ 中的原语初始化类(如 std::字符串从 const char* 初始化)
- std::字符串串联操作
- 如何有效地将一个大std::字符串的一部分转换为float
- 转义std::字符串中的特殊字符
- 用C++替换std::字符串中的一个子字符串,但不能全部替换
- C++std::字符串流到常量字符*的转换
- 如何将std::字符串转换为不同的字符串类
- 对齐C++字符串类型问题 std::字符串到 TStr
- std::字符串到字符*而不切割字节
- 编写具有非ASCII数据的std ::字符串
- 将 Delphi 的字符串转换为 std::字符串用于C++
- std::字符串添加到字符*
- 字符* 和 std::字符串和常量字符*之间的转换
- 用指针访问std ::字符串中的元素