Home > Back-end >  How in multimap run for range from to?
How in multimap run for range from to?

Time:07-08

I need to go from the beginning 3 and from the end -3 that is, if the total size is 10, then I have to iterate from 3 to 7 who it doesnt work?

std::multimap<int,int> _multimap;
for(auto it = _multimap.begin()   3; it != _multimap.end() - 3; it  ) {
    std::cout << it->first;
}

CodePudding user response:

The problem is that the class template std::multimap does not have random access iterators. It has bidirectional iterators.

So you may not write

_multimap.begin()   3

or

_multimap.end() - 3

Instead you could write the for loop the following way using standard function std::next and std::prev

#include <iterator>

//...

for( auto first = std::next( _multimap.begin(), 3 ),
     last = std::prev( _multimap.end(), 3 ); 
     first != last;
       first ) {
    /// TODO: something happen
}

Here is a demonstration program.

#include <iostream>
#include <map>
#include <iterator>

int main()
{
    std::multimap<int, char> m =
    {
        { 65, 'A' }, { 66, 'B' }, { 67, 'C' }, { 68, 'D' }, { 69, 'E' },
        { 70, 'F' }, { 71, 'G' }, { 72, 'H' }, { 73, 'I' }, { 74, 'J' },
    };

    for ( auto first = std::next( std::begin( m ), 3 ), last = std::prev( std::end( m ), 3 );
          first != last;
            first )
    {
        std::cout << first->first << ": " << first->second << '\n';
    }        
}

The program output is

68: D
69: E
70: F
71: G

If you want to have the range of elements [3, 7 ] then instead of

last = std::prev( std::end( m ), 3 )

you need to write

last = std::prev( std::end( m ), 2 )

Do not forget to include the header <iterator>.

  • Related