c++ - 我可以创建具有指定长度但没有初始化的 C++ 字符串/vector 吗?

标签 c++ string vector initialization

我需要创建一个string/vector。我知道它应该有多长,但是,我想稍后将正确的内容写入其中。我可以用指定的长度创建它但没有任何初始化(既不显式也不隐式),就像 malloc 所做的那样吗?因为我会在读取之前正确地写入它,所以在构造时初始化它会浪费时间。

我希望我可以在创建 vector 后以任意顺序编写,比如

vector<int> v(10); // Some magic to create v with 10 of uninitialized ints
v[6] = 1;
v[3] = 2;
...

这似乎是不可能的。

最佳答案

如果我正确理解您的问题,您需要 std::vector::reserve std::basic_string::reserve .

std::vector<int> v;               // empty vector
v.reserve(how_long_it_should_be); // insure the capacity
v.push_back(the_right_thing);     // add elements
...

编辑问题的编辑

vector<int> v(10); , 将始终构造 v有 10 个默认初始化 int ,即 0 .你可能想要 std::array 如果你能在编译时知道大小。

std::array<int, 10> v;  // construct v with 10 uninitialized int
v[6] = 1;
v[3] = 2;

LIVE

关于c++ - 我可以创建具有指定长度但没有初始化的 C++ 字符串/vector 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37317717/

相关文章:

c++ - 了解 Visual Studio 2010 中的此错误 (LNK 2019)

string - 用 sed 替换方括号之间的字符串

c++ - vector vector 的问题是什么?

c++指向基类的 vector 指针,以及访问多个派生类的方法

Java Split 取出单个单词并将它们保存为字符串?

c++ - 模板声明不能出现在 block 范围内

c++ - 除零错误

c++ - 如何将随机(boost.random)库包装在一个类中?

c++ - STL 分配器和运算符 new[]

Python:将复杂的字符串解析成可用的数据进行分析