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