c++ - 为什么 std::set/std::map 和 std::unordered_set/std::unordered_map 没有 std::erase 重载但有 std::erase_if ?

标签 c++ c++20

std::erase/std::erase_if 具有所有序列容器(例如 vector/数组/列表)的重载。但关联容器(例如 set/map)只有 std::erase_if。有人知道为什么吗?

std::erase_if (std::set)

std::erase_if (std::unordered_set)

最佳答案

在原始提案 N4009 中找到了这一点

Design Decision #3: Just predicates, or also values?
This is related to naming. Providing eliminate(container, value) and eliminate_if(container, pred) would be perfectly acceptable. However, providing erase(container, value) in addition to erase_if(container, pred) would be problematic, and has therefore been avoided in this proposal. The problem is that the ordered/unordered associative containers have erase(key) member functions that perform efficient lookups. This could lead to confusion about erase(container, value)'s complexity. (It would have to be a linear scan, even for sets - erase(key) works with operator<() equivalence, but erase(container, value) would have to use operator==(), and they are not required to have any particular relationship.) In contrast, erase_if(container, pred) "sounds like" linear complexity (which it is), even for ordered/unordered associative containers. And of course, lambdas (especially C++14's generic lambdas) make it relatively easy to use erase_if() to eliminate all occurrences of a given value. Informally speaking (i.e. without hard data), I've found that having to erase all occurrences of a particular value is a much less common task than having to erase all elements that satisfy some condition. On the other hand, symmetry would be desirable, and it would prevent users from wondering why one flavor was missing.

关于c++ - 为什么 std::set/std::map 和 std::unordered_set/std::unordered_map 没有 std::erase 重载但有 std::erase_if ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70860670/

相关文章:

C++ 在 Vector 中使用不可赋值的对象

c++ - Qt Creator 无法识别 pro 中的 my 更改。文件

c++ - 如何阻止时间在 Linux 上倒退?

c++ - 使用C++20 Concept约束模板参数

c++ - 为什么 std::strong_ordering 有 `equivalent` 值?

在 gcc 9.3 中编译但不能在 gcc 10.2 中编译的 C++ 代码

c++ - 如何在 C++ 中将 unsigned char[] 打印为 HEX?

Android - native 全局对象析构函数从未被调用

c++ - 为什么 C++ 中的表达式类型在不同版本之间发生变化?

c++ - 如何使用 co_return 从协程返回值?