std::unordered_set::clear(3)

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

πŸ’… std::unordered_set::clear β€” C++ Standard Library, bestie edition

Okay so we're in the C++ Standard Library pages (std::unordered_set::clear(3)), and honestly? This one's a whole mood reset button for your container. Let's get into it ✨


🌸 NAME

std::unordered_set::clear β€” the function that literally just empties your whole set. That's it. That's the function.


πŸŽ€ Synopsis

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

Bestie. It erases all elements from the container. Every last one. After this call, size() returns zero β€” like, actually zero, no crumbs left πŸ‘‘

Also, heads up: it invalidates any references, pointers, and iterators referring to contained elements. And it may also invalidate past-the-end iterators. So if you were holding onto an iterator like it was your emotional support bestie… it's gone now πŸ’€


πŸ¦‹ Parameters

(none) β€” she takes nothing, gives nothing, just vibes 🫢


πŸ“ Return value

(none) β€” void queen behavior, no receipts, no notes πŸ’…


⭐ Complexity

Linear in the size of the container, i.e., the number of elements. So the more stuff you have in there, the longer the goodbye takes. No shortcuts, no cap.


🌈 Example

Okay so here's the actual code, run this:

// Run this code

#include <iostream>
#include <string_view>
#include <unordered_set>

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

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

✨ Possible output

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

Not the Size=0 at the end 😭 she really said "empty" and meant it. Iconic.


🧚 Defect reports

So the following behavior-changing defect reports were applied retroactively to previously published C++ standards. Like a patch note but for the standard itself πŸŽ€

  • 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. Thank you LWG, we were all confused and now we're not πŸ’œ

πŸ‘‘ See also

  • erase β€” erases elements (public member function) β€” if clear is the "delete the whole chat" button, erase is the "remove one specific message" button. Use accordingly πŸ¦‹

✨ and that's the page, bestie ✨ β€” sourced from http://cppreference.com, dated 2024.06.10, from the std::unordered_set::clear(3) page. Go forth and clear responsibly πŸ’–πŸŒΈ

πŸ“¦ where this page comes from