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

ced*_*usx 4 c++ string vector

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

我希望在创建矢量之后可以用任意顺序编写,比如

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

看似那是不可能的.

son*_*yao 7

如果我理解你的问题,你想要std::vector::reservestd::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
...
Run Code Online (Sandbox Code Playgroud)

编辑问题的编辑

vector<int> v(10);,将始终构造v10默认初始化int,即0.std::array如果您在编译时可以知道大小,则可能需要.

std::array<int, 10> v;  // construct v with 10 uninitialized int
v[6] = 1;
v[3] = 2;
Run Code Online (Sandbox Code Playgroud)

生活


Max*_*kin 6

是的,您可以使用boost::noinit_adaptor

vector<int, boost::noinit_adaptor<std::allocator<int>> v(10);
Run Code Online (Sandbox Code Playgroud)

在底层,它重新定义allocator::construct为使用默认初始化new(p) T而不是值初始化 new(p) T()

对于内置类型,默认初始化不执行任何操作,而值初始化则为零初始化。


geo*_*ptr 5

使用.reserve()上无论是集装箱将增加.capacity(),而不调用任何缺省构造函数分配的内存块.

您可以断言容器在您需要时具有正确的容量.capacity().请注意,与第一个返回容器内实际对象的数量之后.size()不同,而秒返回当前内存块无需重新分配即可处理的对象总数..capacity().reserve()

根据std::vector经验.reserve()将容器放在运行时避免额外分配是一种很好的做法(特别是对于).如果你至少使用C++ 11,如果你想要剩余的内存,你可以处理一些复制/移动,你可以使用shrink_to_fit().

请注意,std::string::reservestd::vector::reserve请求的新容量小于当前容量的情况不同.该字符串将把它作为非绑定请求进行收缩,而向量将忽略该请求.