0

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

9
  • So you know what you want to do, where's the problem? Where is the code that's causing an issue? Commented Feb 13, 2018 at 15:11
  • Use std::next to advance the begin iterator. Commented Feb 13, 2018 at 15:12
  • 2
    You know those "old" examples of for(auto it = m.begin(); it != m.end(); ++it)? You can in fact use other iterator values besides begin and end, if you have them. Commented Feb 13, 2018 at 15:12
  • 1
    3rd element: std::next(map.begin(), 2) Commented Feb 13, 2018 at 15:15
  • 1
    5th element std::next(map.begin(), 4) Commented Feb 13, 2018 at 15:17

2 Answers 2

6

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.

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

4 Comments

Worth saving the value of std::next(m.begin(), 5); instead of recalculating it each time round the loop
I wonder, would there be gains in storing the end condition iterator or would compilers be aware enough to optimize the std::next away if the map is not modified withing the loop?
I doubt compilers would be aware enough.
It's important to note that if the map doesn't have at least 5 elements, this will result in undefined behavior. Depending on OP's circumstances, a size check or an assert statement might be appropriate.
1

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)

2 Comments

I just wanted to know if it is possible i m not implementing it anywhere✌
@Rahulmalawadkar everything is possible, question is what is the price.

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.