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
2 Answers
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.
4 Comments
john
Worth saving the value of
std::next(m.begin(), 5); instead of recalculating it each time round the looppatatahooligan
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?john
I doubt compilers would be aware enough.
patatahooligan
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.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
Rahul malawadkar
I just wanted to know if it is possible i m not implementing it anywhere✌
Slava
@Rahulmalawadkar everything is possible, question is what is the price.
std::nextto advance thebeginiterator.for(auto it = m.begin(); it != m.end(); ++it)? You can in fact use other iterator values besidesbeginandend, if you have them.std::next(map.begin(), 2)std::next(map.begin(), 4)