C++ <vector> capacity function

C++ container class <vector>


capacityis used in vector forQuery capacitythe function that returns the size of the storage space currently allocated by the container.

capacityis a member function of container classes, used forReturns the number of elements that the currently allocated storage space of the container can hold. This value is usually greater than or equal tosize()。

capacityReflects the pre-allocated memory space inside the vector; understanding it helps optimize program performance and avoid unnecessary memory reallocation.

Word Definitions: capacityMeans "capacity", that is, the number of elements the container can hold.


Basic syntax and parameters

capacityIs a member function of the container class, and calling it requires no parameters.

Syntax format

size_type capacity() const;

Parameter description

  • Parameter: No parameters
    • capacitydoes not accept any parameters.

Function description

  • Return Value: returnssize_typeType (usuallysize_t), indicating the number of elements that the container's currently allocated storage space can hold.
  • Effect: Returns a non-negative integer representing the memory space allocated by the container.
  • Note: capacity()Returns the capacity, not the number of elements. For the number of elements, usesize()Get.

Example

Let us thoroughly master through a series of examplescapacityUsage.

Example 1: Basic usage - viewing capacity

Example

#include <iostream>
#include <vector>

int main() {
    // Empty vector
    std::vector<int> emptyVec;
    std::cout << "Empty vector - size: " << emptyVec.size()
              << ", capacity: " << emptyVec.capacity() << std::endl;

    // Vector with elements
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    std::cout << "5 element vector - size: " << numbers.size()
              << ", capacity: " << numbers.capacity() << std::endl;

    return 0;
}

Expected result:

空 vector - size: 0, capacity: 0
5 元素 vector - size: 5, capacity: 5

Code analysis:

  1. empty vector'scapacity()is 0.
  2. A vector with 5 elementscapacity()Is at least 5 (may be larger, depending on the implementation).

Example 2: The relationship between size and capacity

UnderstandingsizeandcapacityThe difference is the foundation for optimizing vector usage.

Example

#include <iostream>
#include <vector>

int main() {
    std::vector<int> v;

    // Gradually add elements and observe capacity changes
    std::cout << "Changes in size and capacity during element addition:" << std::endl;

    for(int i = 0; i < 15; ++i) {
        v.push_back(i);
        std::cout << "After adding " << (i + 1) << " elements - size: "
                  << v.size() << ", capacity: " << v.capacity() << std::endl;
    }

    return 0;
}

Expected result (typical output):

添加元素过程中 size 和 capacity 的变化:
添加 1 个元素后 - size: 1, capacity: 1
添加 2 个元素后 - size: 2, capacity: 2
添加 3 个元素后 - size: 3, capacity: 4
添加 4 个元素后 - size: 4, capacity: 4
添加 5 个元素后 - size: 5, capacity: 8
添加 6 个元素后 - size: 6, capacity: 8
添加 7 个元素后 - size: 7, capacity: 8
添加 8 个元素后 - size: 8, capacity: 8
添加 9 个元素后 - size: 9, capacity: 16
添加 10 个元素后 - size: 10, capacity: 16
添加 11 个元素后 - size: 11, capacity: 16
添加 12 个元素后 - size: 12, capacity: 16
添加 13 个元素后 - size: 13, capacity: 16
添加 14 个元素后 - size: 14, capacity: 16
添加 15 个元素后 - size: 15, capacity: 16

Code analysis:

  • The capacity of a vector grows exponentially (usually by a factor of 2).
  • When capacity is insufficient, the vector allocates a larger memory space (usually twice the current capacity).
  • This strategy is to reduce the number of memory reallocations and improve performance.

Example 3: Using reserve to pre-allocate capacity

UsagereserveYou can pre-allocate sufficient capacity to avoid frequent memory reallocation.

Example

#include <iostream>
#include <vector>

int main() {
    // Pre-allocate capacity for 1000 elements
    std::vector<int> v;
    v.reserve(1000);

    std::cout << "After reserve(1000) - size: " << v.size()
              << ", capacity: " << v.capacity() << std::endl;

    // Add 100 elements
    for(int i = 0; i < 100; ++i) {
        v.push_back(i);
    }

    std::cout << "After adding 100 elements - size: " << v.size()
              << ", capacity: " << v.capacity() << std::endl;

    return 0;
}

Expected result:

reserve(1000) 后 - size: 0, capacity: 1000
添加 100 个元素后 - size: 100, capacity: 1000

Code analysis:

  • reserve(1000)Pre-allocated memory space that can hold 1000 elements.
  • After adding 100 elements,capacityIt is still 1000, and no memory reallocation occurred.
  • This can significantly improve performance, especially when a large number of elements need to be added.

Example 4: shrink_to_fit releases excess capacity

C++11 introducedshrink_to_fitmethod, which can adjust the capacity to be the same as size.

Example

#include <iostream>
#include <vector>

int main() {
    std::vector<int> v;

    // Add 5 elements
    for(int i = 0; i < 5; ++i) {
        v.push_back(i);
    }

    std::cout << "Initial state - size: " << v.size()
              << ", capacity: " << v.capacity() << std::endl;

    // Reserve more space
    v.reserve(100);
    std::cout << "After reserve(100) - size: " << v.size()
              << ", capacity: " << v.capacity() << std::endl;

    // Shrink to appropriate size
    v.shrink_to_fit();
    std::cout << "After shrink_to_fit() - size: " << v.size()
              << ", capacity: " << v.capacity() << std::endl;

    return 0;
}

Expected result:

初始状态 - size: 5, capacity: 5
reserve(100) 后 - size: 5, capacity: 100
shrink_to_fit() 后 - size: 5, capacity: 5

Code analysis:

  • shrink_to_fit()Requests the container to reduce capacity to the same as size.
  • This can release memory that is no longer needed.
  • Note: This is not mandatory; the actual capacity depends on the implementation.

Example 5: Practical application of capacity

LearncapacityIt can help optimize memory usage.

Example

#include <iostream>
#include <vector>

void printStatus(const std::string& operation,
                 const std::vector<int>& v) {
    std::cout << operation << " - size: " << v.size()
              << ", capacity: " << v.capacity() << std::endl;
}

int main() {
    std::vector<int> data;

    printStatus("Initial state", data);

    // If we know we need to store 1000 elements, we can pre-allocate
    const size_t estimatedSize = 1000;
    data.reserve(estimatedSize);

    printStatus("After reserve(1000)", data);

    // Simulate data loading
    for(size_t i = 0; i < 1000; ++i) {
        data.push_back(static_cast<int>(i));
    }

    printStatus("After adding 1000 elements", data);

    // Check if capacity expansion is needed
    if(data.capacity() < estimatedSize) {
        std::cout << "Warning: Insufficient capacity!" << std::endl;
    } else {
        std::cout << "Sufficient capacity, minimized memory allocation count" << std::endl;
    }

    return 0;
}

Expected result:

初始状态 - size: 0, capacity: 0
reserve(1000) 后 - size: 0, capacity: 1000
添加 1000 个元素后 - size: 1000, capacity: 1000
容量充足,内存分配次数最少化

Code analysis:

  • Pre-estimate the required capacity and usereservecan avoid multiple memory allocations.
  • This is especially useful for scenarios involving large amounts of data.

C++ container class <vector>

other extensions