简体   繁体   中英

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). What's the best way to achieve this?

Look at the .reserve() member function. The standard docs at the SGI site say

[4] Reserve() causes a reallocation manually. 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. The other reason for using reserve() is so that you can control the invalidation of iterators. [5]

[5] A vector's iterators are invalidated when its memory is reallocated. 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.

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.

You reserve space for vector and string by their reserve(size_type capacity) member function. 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.

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?

Both of them have member function called reserve which you can use to reserve space.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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