0

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;
}
1
  • Recommendation: expand on doesn't work. If you're tripping over a compiler error, add it to the question. In general, produce a minimal reproducible example complete with inputs, expected outputs and actual outputs and see if simply having all that in front of you in one place is enough to see the problem yourself. If it doesn't add it all to the question. Commented Jul 7, 2022 at 21:37

1 Answer 1

2

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>.

Sign up to request clarification or add additional context in comments.

2 Comments

and even if you use vector you will get elements 3 thru 6 not 3 thru 7
@pm100 It is unimportant what range he is going to use. I have taken its expression where it is used -3.:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.