简体   繁体   English

如何为 std::vector/std::string 保留空间?

[英]How do I reserve space for std::vector/std::string?

I'm looking for a way that prevents std::vectors/std::strings from growing in a given range of sizes (say I want to assume that a string will hold around 64 characters, but it can grow if needed).我正在寻找一种方法来防止 std::vectors/std::strings 在给定的大小范围内增长(假设我想假设一个字符串将包含大约 64 个字符,但如果需要它可以增长)。 What's the best way to achieve this?实现这一目标的最佳方法是什么?

Look at the .reserve() member function.查看.reserve()成员 function。 The standard docs at the SGI site say SGI 网站上的标准文档

[4] Reserve() causes a reallocation manually. [4] Reserve() 导致手动重新分配。 The main reason for using reserve() is efficiency: if you know the capacity to which your vector must eventually grow, then it is usually more efficient to allocate that memory all at once rather than relying on the automatic reallocation scheme.使用 reserve() 的主要原因是效率:如果您知道向量最终必须增长到的容量,那么一次分配 memory 通常比依赖自动重新分配方案更有效。 The other reason for using reserve() is so that you can control the invalidation of iterators.使用 reserve() 的另一个原因是您可以控制迭代器的失效。 [5] [5]

[5] A vector's iterators are invalidated when its memory is reallocated. [5] 向量的迭代器在其 memory 被重新分配时失效。 Additionally, inserting or deleting an element in the middle of a vector invalidates all iterators that point to elements following the insertion or deletion point.此外,在向量中间插入或删除元素会使指向插入或删除点之后的元素的所有迭代器无效。 It follows that you can prevent a vector's iterators from being invalidated if you use reserve() to preallocate as much memory as the vector will ever use, and if all insertions and deletions are at the vector's end.因此,如果您使用 reserve() 预分配与向量将使用的一样多的 memory,并且如果所有插入和删除都在向量的末尾,则可以防止向量的迭代器失效。

That said, as a general rule unless you really know what is going to happen, it may be best to let the STL container deal with the allocation itself.也就是说,作为一般规则,除非您真的知道会发生什么,否则最好让 STL 容器自己处理分配。

You reserve space for vector and string by their reserve(size_type capacity) member function.你通过他们的reserve(size_type capacity)成员function为vectorstring预留空间。 But it doesn't prevent it from anything:).但这并不能阻止它做任何事情:)。 You're just telling it to allocate at least that much of uninitialized memory (that is, no constructors of your type will be called) and resize to more if needed.您只是告诉它分配至少那么多未初始化的 memory (也就是说,不会调用您类型的构造函数)并在需要时调整大小。

std::vector<MyClass> v;
v.reserve(100); //no constructor of MyClass is called
for(int i = 0; i < 100; ++i)
{
    v.push_back(MyClass()); // no reallocation will happen. There is enough space in the vector
}

For vector:对于矢量:

std::vector<char> v;
v.reserve(64);

For string:对于字符串:

std::string s;
s.reserve(64);

Where's your C++ Standard Library reference got to?您的 C++ 标准库参考在哪里?

Both of them have member function called reserve which you can use to reserve space.它们都有名为reserve的成员 function ,您可以使用它来预留空间。

c.reserve(100); //where c is vector (or string)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM