Iterate over all the elements in a std::multimap with the same key

250 Views Asked by At

I want to add objects so a multi-map and some should have the same key how can I get access to all the elements which the same key?

Can I do a ranged fore lope over only the specific keys or something similar?

1

There are 1 best solutions below

0
Caleth On BEST ANSWER

You can use the equal_range member, and wrap that in a ranges::subrange to range-for over it.

auto range = map.equal_range(key); 
for (auto & [_, value] : std::ranges::subrange(range.first, range.second)) {
    // ...
}

When ranged-for was being proposed, it was considered to let std::pair<iter, iter> be directly iterated over, but that was rejected as potentially dangerous.

See it on coliru