简体   繁体   中英

Why std::set / std::map and std::unordered_set / std::unordered_map does NOT have std::erase overload but have std::erase_if?

std::erase / std::erase_if have overloads for all sequence containers (egvector / array / list). But associative containers (eg set / map) only have std::erase_if . Anyone knows why?

std::erase_if (std::set)

std::erase_if (std::unordered_set)

Found this in the original proposal 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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM