std::vector::capacity(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

✨ std::vector::capacity ✨

Okay bestie, welcome to the std::vector::capacity page from the C++ Standard Library manual. This is the glow-up guide you didn't know you needed, and yes, we're gonna read the whole thing. πŸ’…


SYNOPSIS πŸŽ€

size_type capacity() const;  (noexcept since C++11)
                             (constexpr since C++20)

Returns the number of elements that the container has currently allocated space for.


PARAMETERS 🌸

(none) β€” literally nothing, bestie. Zero. Nada. The function takes no arguments, periodt. πŸ’–


RETURN VALUE ✨

Capacity of the currently allocated storage.

Like, it's the number of elements your vector could hold before it has to go reallocate and do the whole dramatic growth spurt. No cap. πŸ¦‹


COMPLEXITY πŸ”₯

Constant. O(1), baby. It's a one-and-done. Constant time, always. πŸ’€


EXAMPLE πŸ‘‘

// Run this code

#include <iomanip>
#include <iostream>
#include <vector>

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

    auto cap = v.capacity();
    std::cout << "Initial size: " << v.size() << ", capacity: " << cap
<< '\n';

    std::cout << "\nDemonstrate the capacity's growth policy."
                 "\nSize:  Capacity:  Ratio:\n" << std::left;
    while (sz-- > 0)
    {
        v.push_back(sz);
        if (cap != v.capacity())
        {
            std::cout << std::setw( 7) << v.size()
                      << std::setw(11) << v.capacity()
                      << std::setw(10) << v.capacity() /
static_cast<float>(cap) << '\n';
            cap = v.capacity();
        }
    }

    std::cout << "\nFinal size: " << v.size() << ", capacity: " <<
v.capacity() << '\n';
}

Possible output:

Initial size: 0, capacity: 0

Demonstrate the capacity's growth policy.
Size:  Capacity:  Ratio:
1      1          inf
2      2          2
3      4          2
5      8          2
9      16         2
17     32         2
33     64         2
65     128        2

Final size: 100, capacity: 128

The way this snippet literally shows the growth policy is giving main character energy. The ratio goes inf first because you're dividing by zero capacity, and then it's all 2s. Iconic. 🌈


SEE ALSO 🫢

  • size β€” returns the number of elements (public member function)
  • reserve β€” reserves storage (public member function)

πŸ’‘ Quick vibe check: noexcept since C++11 and constexpr since C++20. Don't forget those version notes, bestie. They're important. 😭

Source: http://cppreference.com β€” Version: 2024.06.10 β€” Manual: std::vector::capacity(3)

Stay slay, stay constant, and may your capacity always be enough. Bye bestie! πŸ’œβœ¨πŸŽ€

πŸ“¦ where this page comes from