std::map::clear(3)

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

hii bestie πŸ’– you just opened the std::map::clear page from the C++ Standard Libary (yes, β€œLibary” β€” that’s literally how the header spells it, and we respect the typo πŸ’€). it’s manual-page time, but make it cute.

✨ NAME ✨

std::map::clear β€” std::map::clear. that’s the name. that’s it. iconic minimalism πŸ’…

πŸ¦‹ Synopsis πŸ¦‹

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

okay so what does it actually do? it erases all elements from the container 🧹✨. after this call, size() returns zero β€” like, completely empty, not a single element left. bye bestie πŸ‘‹

and heads up: it invalidates any references, pointers, and iterators referring to contained elements 😭. but the good news? any past-the-end iterator remains valid 🫢.

🌸 Parameters 🌸

(none) β€” nothing to pass in. zero. nada. it’s a no-argument situation 🫢.

πŸŽ€ Return value πŸŽ€

(none) β€” it doesn’t hand anything back, it just clears and dips ✨.

⭐ Complexity ⭐

Linear in the size of the container, i.e., the number of elements. so the more stuff you’re clearing, the more work it does. periodt.

πŸ”₯ Example πŸ”₯

the original page says // Run this code β€” so go off, run it bestie πŸ’…

#include <iostream>
#include <string_view>
#include <map>

void print_info(std::string_view rem, const std::map<int, char>& v)
{
    std::cout << rem << "{ ";
    for (const auto& [key, value] : v)
        std::cout << '[' << key << "]:" << value << ' ';
    std::cout << "}\n";
    std::cout << "Size=" << v.size() << '\n';
}

int main()
{
    std::map<int, char> container{{1, 'x'}, {2, 'y'}, {3, 'z'}};
    print_info("Before clear: ", container);
    container.clear();
    print_info("After clear: ", container);
}

🌈 Output 🌈

Before clear: { [1]:x [2]:y [3]:z }
Size=3
After clear: { }
Size=0

πŸ’€ Defect reports πŸ’€

The following behavior-changing defect reports were applied retroactively to previously published C++ standards. (retroactively!! the committee really said β€œwe’ll fix it later” and honestly same πŸ™ˆ)

  • DR LWG 224
  • Applied to C++98
  • Behavior as published the complexity was log(size()) + N, but N was not defined
  • Correct behavior corrected to 'linear in size()'

πŸ‘‘ See also πŸ‘‘

  • erase β€” erases elements (public member function).

mwah πŸ’‹ this masterpiece lives at http://cppreference.com and is dated 2024.06.10. now go clear that map, bestie β€” you’re literally gonna slay 🫢✨

πŸ“¦ where this page comes from