Compare two consecutive elements in std :: list

I would like to compare two consecutive elements in std :: list, iterating through a list. What is the correct way to access element i + 1 while my iterator is in element i? thanks kob

+5
source share
5 answers

Boost has a utility called next(and its reverse, prior) for this purpose only.

*itr == *next(itr)

Edit: , , , , custom-write adjacent_find ? ( , .) STL Boost, Boost ( ).

+10

STL adj_find(), . .

:

template <class ForwardIterator>
   ForwardIterator adjacent_find ( ForwardIterator first, ForwardIterator last );

template <class ForwardIterator, class BinaryPredicate>
   ForwardIterator adjacent_find ( ForwardIterator first, ForwardIterator last,
                                   BinaryPredicate pred );
+10

( ).

std::list<int>::const_iterator second = list.begin(),
                               end = list.end();

if ( second != end ) // Treat empty list
    for(std::list<int>::const_iterator first = second++; // Post-increment 
        second != end; 
        ++first, ++second)
    {
        //...
    }

, first post-incrementation second, , first, list.begin(), - list.begin()+1.

- , boost next prior, ( ), ( , list ).

template <class Iterator>
Iterator next(Iterator i) // Call by value, original is not changed
{ 
    return ++i;
}
// Implementing prior is left as an exercise to the reader ;o) 

, next , , , next(i) end() .


:

+8

The list is a reversible container, so its iterators are bidirectional iterators, which are the Forward Iterator model, and I'm sure you can do it (or something similar if you are allergic to break out of the middle of the loop, etc.):

if (!l.empty()) {
    for (list<T>::const_iterator i = l.begin();;) {
        const T &a = *i;
        ++i;
        if (i == l.end()) break;
        do_comparison(a, *i);
    }
}

You could not do this with the Input Iterator, because with those values ​​only β€œexist” if you have an iterator. But you can using Forward Iterator.

+1
source
for (list<int>::iterator it = test.begin(); it!=test.end(); it++) {
        cout<<*it<<":\t";
        list<int>::iterator copy = it;
        for( list<int>::iterator it2 =  ++copy; it2!=test.end();it2++){
            cout<<*it2<<"\t";
        }
        cout<<endl;
    }
0
source

All Articles