std::unordered_map::clear(3)

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

πŸ’– NAME

okay so this page is std::unordered_map::clear β€” and the NAME line is literally std::unordered_map::clear - std::unordered_map::clear, no cap 😭. It's from the C++ Standard Libary manual (yes, that's the spelling in the header, bestie πŸ’€), title std::unordered_map::clear(3). This is the member function that wipes an unordered map clean. ✨

✨ Synopsis

void clear() noexcept;

(since C++11) πŸŽ€

Erases all elements from the container. After this call, size() returns zero.

It invalidates any references, pointers, and iterators referring to contained elements. It may also invalidate past-the-end iterators. 🫢

🌸 Parameters

(none) β€” literally nothing to pass, bestie. πŸ’…

πŸ’œ Return value

(none) β€” it's a void vibe. 🫢

πŸ”₯ Complexity

Linear in the size of the container, i.e., the number of elements. So it scales with the element count, periodt. πŸ“

🌈 Example

// Run this code

#include <iostream>
#include <string_view>
#include <unordered_map>

void print_info(std::string_view rem, const std::unordered_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::unordered_map<int, char> container{{1, 'x'}, {2, 'y'}, {3, 'z'}};
    print_info("Before clear: ", container);
    container.clear();
    print_info("After clear: ", container);
}

🌟 Possible 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. (Retroactive lore drop, bestie. 😭)

  • DR: LWG 2550
  • Applied to: C++11
  • Behavior as published: for unordered associative containers, unclear if complexity is linear in the number of elements or buckets
  • Correct behavior: clarified that it's linear in the number of elements

🫢 See also

  • erase β€” erases elements (public member function) πŸ‘‘

source/version + date sign-off: big shoutout to http://cppreference.com, dated 2024.06.10, for the std::unordered_map::clear(3) page πŸ’–βœ¨

πŸ“¦ where this page comes from