c++iteratorunordered-mapunordered-multimap

Is there a way to convert local_iterator to const_iterator or iterator?


How can we change unordered_multimap::local_iterator to unordered_multimap::iterator or unordered_multimap::const_iterator? I need the change because we cannot erase elements using local_iterator, and erasing can only be done using iterator/const_iterator. If there is any other way of erasing using local_iterator, please do suggest.


Solution

  • Kinda labor intensive, but you can iterate through the result of equal_range() until you find the correct iterator:

    template<typename Cont>
    typename Cont::iterator local_to_regular_iterator(Cont& c, typename Cont::local_iterator local_ite) {
      auto range = c.equal_range(local_ite->first);
    
      for(auto ite = range.first; ite != range.second; ++ite) {
        if(&ite->second == &local_ite->second) {
          return ite;
        }
      }
    
      throw std::out_of_range("huh?");
    }
    

    As far as I can tell, that's as good as you can get currently.