std::forward_list::clear(3)
β¨ 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.
DRLWG 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
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms