rsk82
rsk82

Reputation: 29377

how to iterate multimap backwards for unique key?

I know how to do it forward:

for(auto it = mmap.begin(), end = mmap.end(); it != end; it = mmap.upper_bound(it->first))

but this doesn't work:

for(auto it = mmap.rbegin(), end = mmap.rend(); it != end; it = mmap.lower_bound(it->first))

giving: error: no match for 'operator=' in 'it = mmap.std::multimap<_Key, _Tp, _Compare, _Alloc>::lower_bound<unsigned int, long int, std::less<unsigned int>, std::allocator<std::pair<const unsigned int, long int> > >((* & it.std::reverse_iterator<_Iterator>::operator-><std::_Rb_tree_iterator<std::pair<const unsigned int, long int> > >()->std::pair<const unsigned int, long int>::first))'

Upvotes: 1

Views: 1801

Answers (1)

Joseph Mansfield
Joseph Mansfield

Reputation: 110658

A std::multimap::iterator is not directly convertible to a std::reverse_iterator. You need to make the result of std::lower_bound the base iterator of it:

typedef ... multimap_type;
typedef std::reverse_iterator<multimap_type::iterator> reverse_iterator;

for (auto it = mmap.rbegin(),
          end = mmap.rend();
     it != end;
     it = reverse_iterator(mmap.lower_bound(it->first)))
{
  // ...
}

The expression reverse_iterator(mmap.lower_bound(it->first)) will construct a std::reverse_iterator with the result of lower_bound as its base iterator.

Upvotes: 3

Related Questions