std::hive<T,Allocator>::reserve
void reserve( size_type new_cap ); | (since C++26) |
Increase the capacity of the hive (the total number of elements that the hive can hold without requiring reallocation) to a value that's greater or equal to new_cap. If new_cap is greater than the current capacity(), reserved blocks are allocated, otherwise the function does nothing.
reserve() does not change the size of the hive.
After a call to reserve(), capacity() >= new_cap is true.
All iterators (including the end() iterator), pointers and references to the elements of the container remain valid.
Parameters
| new_cap | - | new capacity of the hive, in number of elements |
Exceptions
-
std::length_errorifnew_cap >= max_size. - Any exception thrown by
Allocator::allocate()(typicallystd::bad_alloc).
Complexity
Linear in the number of allocated reserved blocks.
Notes
reserve() cannot be used to reduce the capacity of the container; to that end shrink_to_fit() and trim_capacity() are provided.
Example
#include <hive>
#include <print>
int main()
{
constexpr int max_elements = 1'000;
std::println("Using reserve:");
{
std::hive<int> h;
h.reserve(max_elements);
for (int n{}; n != max_elements; ++n)
h.insert(n);
std::println("size(): {}, capacity(): {}", h.size(), h.capacity());
}
std::println("Not using reserve:");
{
std::hive<int> h;
for (int n{}; n != max_elements; ++n)
{
if (h.size() == h.capacity())
std::println("size() == capacity() == {}", h.size());
h.insert(n);
}
std::println("size(): {}, capacity(): {}", h.size(), h.capacity());
}
}
Possible output:
Using reserve: size(): 1000, capacity(): 1000 Not using reserve: size() == capacity() == 0 size() == capacity() == 76 size() == capacity() == 152 size() == capacity() == 304 size() == capacity() == 559 size() == capacity() == 814 size(): 1000, capacity(): 1069
See also
| returns the number of elements that can be held in currently allocated storage (public member function) |
|
| returns the maximum possible number of elements (public member function) |
|
| reduces memory usage by freeing unused memory (public member function) |
|
| deallocates reserved blocks and reduces capacity accordingly (public member function) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/cpp/container/hive/reserve