I just noticed that std::map
and std::set
have the member function equal_range()
returning an iterator range of values for a certain key. How does this make sense when std::map
and std::set
are always ordered key/value (as in a single key for a single value, or both combined) containers.
I would expect this member function with std::multimap
and std::multiset
since both of these allow for multiple values sharing the same key, and of course they both do. What am I missing?
It makes sense as conformity with other associative container. Similarly std::map
and std::set
have a count
method even though they can only return 0
or 1
and find
does the job already. You can use count
with associative container no matter if they can have more than 1 same element (cf. std::multi_map
). And you can use equal_range
for a std::unordered_map
in the same way as you can use it for a ordered std::map
. You are right that for a std:map
and std::set
those are rarely useful, but suppose you write generic code that accepts an associative container (ordered or not):
template <typename T,typename E>
void foo(T& t,E e) {
auto p = t.equal_range(e);
//...
}
There is no formal requirement that all associative container must have equal_range
but since c++20 you can write a concept that requires T
must have equal_range
and use the template foo
also with std::map
.