std::erase_if(std::map)(3)

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

πŸ’– NAME πŸ’–

Bestie, welcome to std::erase_if(std::map)(3) β€” the page is literally named std::erase_if(std::map) - std::erase_if(std::map). It lives in the C++ Standard Libary manual (yes, that's the header's spelling 😭), section 3. It's giving "erase the map elements that match your vibe" energy, and honestly? Obsessed. πŸ’…βœ¨


✨ Synopsis ✨

Defined in header <map> β€” that's her home address πŸ πŸ’–

template< class Key, class T, class Compare, class Alloc,
          class Pred >
std::map<Key, T, Compare, Alloc>::size_type
erase_if( std::map<Key, T, Compare, Alloc>& c,
          Pred pred );

(since C++20) πŸ‘‘ β€” so if your setup is pre-C++20, she simply does not exist yet, no cap.

It erases all elements that satisfy the predicate pred from c β€” if pred says true, that element is getting evicted, periodt 🫢

Equivalent to this exact code block, bestie:

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. Bye elements πŸ‘‹πŸ’–
  • pred β€” predicate that returns true if the element should be erased. If it returns true, it's getting the boot πŸ’…

🌸 Return value 🌸

The number of erased elements. That's it, that's the return value β€” a little count of how many cuties got removed 🫢


πŸ¦‹ Complexity πŸ¦‹

Linear. Periodt. ✨


πŸ“ Example πŸ“

// Run this code β€” go ahead bestie, run it πŸ’»πŸ’–

#include <iostream>
#include <map>

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

int main()
{
    std::map<int, char> data
    {
        {1, 'a'}, {2, 'b'}, {3, 'c'}, {4, 'd'},
        {5, 'e'}, {4, 'f'}, {5, 'g'}, {5, 'g'},
    };
    println("Original:\n", data);

    const auto count = std::erase_if(data, [](const auto& item)
    {
        auto const& [key, value] = item;
        return (key & 1) == 1;
    });

    println("Erase items with odd keys:\n", data);
    std::cout << count << " items removed.\n";
}

Output:

Original:
{{1, a}, {2, b}, {3, c}, {4, d}, {5, e}}
Erase items with odd keys:
{{2, b}, {4, d}}
3 items removed.

🌈 See also 🌈

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

okay that's a wrap, bestie πŸ«ΆπŸ’‹ source: http://cppreference.com Β· version/date: 2024.06.10 Β· manual page: std::erase_if(std::map)(3). mwah πŸ’…βœ¨

πŸ“¦ where this page comes from