I have a map of elements and a nested loop to iterate over it. But I want the iterator to behave something like this :
map<int,int>::iterator it;
map<int,int>::iterator it1;
bool flag=false;
for(it=m.begin();it!= m.end()-1;it++)
{
for(it1 = it+1;it1 != m.end();it1++)
{
if((it->first < it1->first)&&(it->second > it1->second))
{
flag=true;
break;
}
}
}
Basically, the outer loop should start terminate at the last but one postion and the inner loop must start iterating from where the outer-loop iterator is. But this code does not seem to work.(No Match for + in it+1) is not defined Any help would be much appreciated. (Please point out any duplicate links as I could not find one for map.) Thanks !
The std::map<K,V,C,A>::iterator
is a bidirectional iterator, which means it does not provide operator+
neither operator-
(only operator++
and operator--
in both prefix and postifx form).
In c++11 it is still possible to shift the iterator using std::next()
or std::prev()
:
for (it = m.begin(); it != std::prev(m.end()); ++it)
// ~~~~~~~~^ instead of m.end()-1
{
for (it1 = std::next(it); it1 != m.end(); ++it1)
// ~~~~~~~~^ to get the it+1
In c++03 you can use std::advance()
instead to move forward/backward by a given interval (the difference is that it operates on an actual object rather than creates a copy like std::next
):
it1 = it;
for (std::advance(it1, 1); it1 != m.end(); ++it1)
// ~~~~~~^ ^ number of steps
Both methods provide the most optimal way to increment/decrement a given iterator (based on that iterator's traits).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With