Spec-Zone.ru › C++

std::hive<T,Allocator>::shrink_to_fit

void shrink_to_fit();
(since C++26)

Requests to reduce capacity() to be closer to size().

It is a non-binding request to reduce the memory usage without changing the size of the hive. It depends on the implementation whether the request is fulfilled.

May reduce (but not increase) capacity and may reallocate elements. If capacity is already equal to size, does nothing.

If reallocation happens, the order of the elements in *this may change and all references and iterators (including end()) referring to elements in *this are invalidated.

If T is not MoveInsertable into std::hive<T, Allocator>, the behavior is undefined.

Complexity

If reallocation happens, linear in the size of the hive.

Exceptions

If an exception is thrown during allocation of a new element block, capacity may be reduced and reallocation may occur. Otherwise, if an exception is thrown, the effects are unspecified.

If an exception is thrown, the order of elements in *this is unspecified.

Example

#include <hive>
#include <print>

int main()
{
    std::hive<int> hive;
    std::println("Default-constructed capacity is {}", hive.capacity());
    hive.insert(100, 0);
    std::println("Capacity after inserting 100 elements is {}", hive.capacity());
    for (auto i{0}; i != 42; ++i)
        hive.erase(hive.begin());
    std::println("Capacity after erasing 42 elements is {}, size is {}",
                 hive.capacity(), hive.size());
    hive.shrink_to_fit();
    std::println("Capacity after shrink_to_fit() is {}", hive.capacity());
}

Possible output:

Default-constructed capacity is 0
Capacity after inserting 100 elements is 100
Capacity after erasing 42 elements is 100, size is 58
Capacity after shrink_to_fit() is 76

See also

trim_capacity
deallocates reserved blocks and reduces capacity accordingly
(public member function)
capacity
returns the number of elements that can be held in currently allocated storage
(public member function)
size
returns the number of elements
(public member function)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/cpp/container/hive/shrink_to_fit

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API