std::erase_if(std::map)(3)
π 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 returnstrueif 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 criteriaremove_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
- 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