c++stdmultimap

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


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?


Solution

  • 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