Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterator for a map from a particular position in C++

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 !

like image 557
Utsav T Avatar asked Feb 12 '23 00:02

Utsav T


1 Answers

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

like image 163
Piotr Skotnicki Avatar answered Feb 16 '23 02:02

Piotr Skotnicki