Rahul malawadkar
Rahul malawadkar

Reputation: 11

How do i use the for loop for a specified range while using maps in c++

I want to use the for loops with iterators while using maps and want to run it for a specified range not from begin() end end(). I would want to use it for a range like from 3rd element to 5th element

Upvotes: 0

Views: 70

Answers (2)

Slava
Slava

Reputation: 44278

This code should be pretty optimal and safe for corner cases:

int count = 0;
for( auto it = m.begin(); it != m.end(); ++it ) {
    if( ++count <= 3 ) continue;
    if( count > 5 ) break;
    // use iterator
}

but the fact you are iterating an std::map this way shows most probably you are using a wrong container (or your logic for 3rd to 5th element is wrong)

Upvotes: 1

Mateusz Grzejek
Mateusz Grzejek

Reputation: 12118

I would want to use it for a range like from 3rd element to 5th element

Since std::map's iterator is not a RandomAccessIterator, but only a BidirectionalIterator (you cannot write .begin() + 3), you can use std::next for this purpose:

for (auto it = std::next(m.begin(), 2); it != std::next(m.begin(), 5); ++it)
{
  // ...
}

And remember - check your ranges to ensure, that you iterate over a valid scope.

Upvotes: 6

Related Questions