std::forward_list::clear(3)

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

✨ std::forward_list::clear ✨

okay bestie, welcome to the std::forward_list::clear glow-up πŸ’… this is a C++ Standard Library page and we're gonna make it make sense, fr fr.

🌸 SYNOPSIS 🌸

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

It literally deletes every single element in the container. All of them. Gone. No cap. 🫢

So any references, pointers, or iterators pointing to stuff inside get invalidatedβ€”like, they're not safe anymore. But the past-the-end iterator stays valid, so that one's still your friend. ✨

πŸŽ€ PARAMETERS πŸŽ€

(none)

Like, there are literally no arguments. It takes nothing. It just clears. Iconic behavior. πŸ‘‘

πŸ¦‹ RETURN VALUE πŸ¦‹

(none)

It doesn't return anything either. It just does the thing and leaves. Main character energy, honestly.

πŸ’– COMPLEXITY πŸ’–

Linear in the size of the container, i.e., the number of elements.

So it's O(n) vibesβ€”the more elements you have, the more work it does. It's not doing some sneaky O(1) magic, it's actually walking through everything. Respect the honesty. πŸ’―

🌈 EXAMPLE 🌈

// Run this code

#include <iostream>
#include <string_view>
#include <forward_list>

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

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

⭐ Output:

Before clear: { 1 2 3 }
After clear: { }

Look at that. Before: full of ints. After: empty. The clear really cleared. Slay. πŸ”₯

πŸ”₯ Defect reports πŸ”₯

okay so there were some behavior-changing defect reports applied retroactively to previously published C++ standards, and we gotta talk about them because they're lowkey important ✨

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
  • DR LWG 2231 β€” Applied to: C++11 β€” the complexity guarantee was mistakenly omitted in C++11, but it got reaffirmed as linear. So yeah, that's a thing that happened. πŸ’€

🧚 See also 🧚

  • erase_after β€” erases an element after an element (public member function). lowkey obsessed with that one too, iykyk 🌸

okay bestie that's the whole page πŸ’œ this was std::forward_list::clear(3) from the C++ Standard Library, brought to you by http://cppreference.com, version 2024.06.10. periodt. πŸŽ€βœ¨

πŸ“¦ where this page comes from