Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to manage the capacity of containers

Shulou Source: shulou.com Published: 2022-06-01 19:23:56 11月12日 Update

This article introduces the knowledge of "how to manage the capacity of containers". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Capacity and size

It is important to understand the difference between capacity and size. The size of a container refers to the number of data that has been stored in the container, while capacity refers to the maximum number of data that the container can contain without reallocating memory. For example, a bottle with a capacity of 2 liters is filled with 1 liter of water. 2 liters is capacity,1 and liter is size.

Manage the capacity of the container

In most cases, programmers do not have to pay attention to the details of container class memory management and leave the work to the C++ standard library. But sometimes there are exceptions:

The response to the required operation is too fast to ignore the time it takes to request memory from the heap.

The space used is so large that you don't want the container to keep extra memory space.

At this point, it is necessary to actively intervene in the acquisition and release of memory. The C++ standard library provides corresponding member functions for this purpose.

Capacity: get the capacity of the container

Size: gets the number of data that has been saved in the container.

Reserve: allocates memory space that can hold at least a specified number of elements.

Shrink_to_fit: frees up excess memory space, leaving only the minimum memory that can hold the data in the container.

Sample code

Vector v

There is no element in / / v, capacity is 0

Cout

Tags: Containers memory space capacity elements data management number allocation content situation more standard knowledge Cellular practical minimum important active for this Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn NVidia Microsoft Apple MariaDB