std::erase_if (std::unordered_map)

来自cppreference.com

 
 
 
 
在标头 <unordered_map> 定义
template< class Key, class T, class Hash, class KeyEqual, class Alloc, class Pred >

typename std::unordered_map<Key, T, Hash, KeyEqual, Alloc>::size_type

    erase_if(std::unordered_map<Key, T, Hash, KeyEqual, Alloc>& c, Pred pred);
(C++20 起)

从容器中擦除所有满足谓词 pred 的元素。等价于

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

参数

c - 要从中擦除的元素
pred - 若应该擦除元素则对它返回 true 的谓词

返回值

擦除的元素数。

复杂度

线性。

示例

#include <unordered_map>
#include <iostream>
 
template<typename Os, typename Container>
inline Os& operator<<(Os& os, Container const& cont)
{
    os << "{";
    for (const auto& item : cont) {
        os << "{" << item.first << ", " << item.second << "}";
    }
    return os << "}";
}
 
int main()
{
    std::unordered_map<int, char> data {{1, 'a'},{2, 'b'},{3, 'c'},{4, 'd'},
                                        {5, 'e'},{4, 'f'},{5, 'g'},{5, 'g'}};
    std::cout << "Original:\n" << data << '\n';
 
    const auto count = std::erase_if(data, [](const auto& item) {
        auto const& [key, value] = item;
        return (key & 1) == 1;
    });
 
    std::cout << "Erase items with odd keys:\n" << data << '\n'
              << count << " items removed.\n";
}

输出:

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

参阅

移除满足特定判别标准的元素
(函数模板)