std::erase_if (std::unordered_multimap)
来自 cppreference.com
定义在头文件 <unordered_map> 中 |
||
template< class Key, class T, class Hash, class KeyEqual, class Alloc, class Pred > |
(自 C++20 起) | |
从 c 中删除所有满足谓词 pred 的元素。
等同于
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();
内容 |
[编辑] 参数
c | - | 要删除元素的容器 |
pred | - | 谓词,如果元素应该被删除,则返回 true |
[编辑] 返回值
删除的元素数量。
[编辑] 复杂度
线性。
[编辑] 示例
运行此代码
#include <iostream> #include <unordered_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::unordered_multimap<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"; }
可能的输出
Original: {{5, g}, {5, g}, {5, e}, {4, f}, {4, d}, {3, c}, {2, b}, {1, a}} Erase items with odd keys: {{4, f}, {4, d}, {2, b}} 5 items removed.
[编辑] 另请参阅
删除满足特定条件的元素 (函数模板) | |
(C++20)(C++20) |
删除满足特定条件的元素 (niebloid) |