std::vector::clear(3)

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

πŸŽ€ NAME πŸŽ€

std::vector::clear β€” literally std::vector::clear (yes bestie, the name is the name πŸ’…). This is the std::vector::clear(3) page from the C++ Standard Libary πŸ’–.

✨ Synopsis ✨

void clear();  (noexcept since C++11)
               (constexpr since C++20)

Okay so clear() erases all elements from the container. After this call, size() returns zero. Slay.

It invalidates any references, pointers, and iterators referring to contained elements. Any past-the-end iterators are also invalidated. So those handles are literally done after this πŸ’€.

It leaves the capacity() of the vector unchanged. (Note: the standard's restriction on the changes to capacity() is in the specification of reserve(), see SO.)

🌸 Parameters 🌸

(none) β€” zero arguments, zero stress, bestie 😌.

πŸ’œ Return value πŸ’œ

(none) β€” it hands you nothing back, and that is correct 🫢.

πŸ¦‹ Complexity πŸ¦‹

Linear in the size of the container, i.e., the number of elements. It's giving linear-in-the-number-of-elements energy, no cap ✨.

πŸ“ Example πŸ“

// Run this code

#include <iostream>
#include <string_view>
#include <vector>

void print_info(std::string_view rem, const std::vector<int>& v)
{
    std::cout << rem << "{ ";
    for (const auto& value : v)
        std::cout << value << ' ';
    std::cout << "}\n";
    std::cout << "Size=" << v.size() << ", Capacity=" << v.capacity()
       << '\n';
}

int main()
{
    std::vector<int> container{1, 2, 3};
    print_info("Before clear: ", container);
    container.clear();
    print_info("After clear: ", container);
}

πŸ–¨οΈ Output: πŸ–¨οΈ

Before clear: { 1 2 3 }
Size=3, Capacity=3
After clear: { }
Size=0, Capacity=3

🧚 Defect reports 🧚

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

  • DR: LWG 2231
    • Applied to: C++11
    • Behavior as published: complexity guarantee was mistakenly omitted in C++11
    • Correct behavior: complexity reaffirmed as linear

🌈 See also 🌈

  • erase erases elements (public member function) ✨

Mwah πŸ’‹ this page came from http://cppreference.com, dated 2024.06.10, and it's the std::vector::clear(3) page. Bye bestie, go clear some vectors responsibly 🫢✨

πŸ“¦ where this page comes from