std::erase_if(std::set)(3)

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

πŸ’– NAME πŸ’–

okay so bestie, this is the page for std::erase_if(std::set) β€” from the C++ Standard Libary manual, with the (3) right there in the header (yes, β€œLibary” is literally how it’s spelled in the header, and we respect the lore 😭). The NAME line is also doing its little mirror thing: std::erase_if(std::set) - std::erase_if(std::set). Iconic. No notes.


πŸ¦‹ Synopsis πŸ¦‹

Defined in header <set> β€” and here’s the exact signature, no cap:

template< class Key, class Compare, class Alloc,

          class Pred >
std::set<Key, Compare, Alloc>::size_type          (since C++20)
    erase_if( std::set<Key, Compare, Alloc>& c,

              Pred pred );

Translation: it erases all elements that satisfy the predicate pred from c. Slay.

Equivalent to:

auto old_size = c.size();
for (auto first = c.begin(), last = c.end(); first != last;)
{
    if (pred(*first))
        first = c.erase(first);
    else
        ++first;
}
return old_size - c.size();

πŸŽ€ Parameters πŸŽ€

  • c β€” container from which to erase. (that’s the whole description, bestie πŸ’…)
  • pred β€” predicate that returns true if the element should be erased. (yes, true means β€œyeet this one” ✨)

πŸ’… Return value πŸ’…

The number of erased elements. That’s it. Periodt.


⚑ Complexity ⚑

Linear. Linear. That’s the whole vibe check. 🌈


🌸 Example 🌸

// Run this code πŸ‘‡

#include <iostream>
#include <set>

void println(auto rem, auto const& container)
{
    std::cout << rem << '{';
    for (char sep[]{0, ' ', 0}; const auto& item : container)
        std::cout << sep << item, *sep = ',';
    std::cout << "}\n";
}

int main()
{
    std::set data{3, 3, 4, 5, 5, 6, 6, 7, 2, 1, 0};
    println("Original:\n", data);

    auto divisible_by_3 = [](auto const& x) { return (x % 3) == 0; };

    const auto count = std::erase_if(data, divisible_by_3);

    println("Erase all items divisible by 3:\n", data);
    std::cout << count << " items erased.\n";
}

πŸ“ Output: πŸ“

Original:
{0, 1, 2, 3, 4, 5, 6, 7}
Erase all items divisible by 3:
{1, 2, 4, 5, 7}
3 items erased.

πŸ‘‘ See also πŸ‘‘

  • remove β€” removes elements satisfying specific criteria
  • remove_if (function template)

source/version check, bestie: this page is from cppreference.com, dated 2024.06.10, and it’s the std::erase_if(std::set)(3) page β€” bye, love you, hydrate and erase responsibly πŸ’–βœ¨πŸ«Ά

πŸ“¦ where this page comes from