简体   繁体   中英

Reverse Iterator Arithmetic

All, I'm trying to do an O(n^2) comparison between elements in a list in reverse, so I'm using a reverse iterator.

Code follows

#include <list>

struct Element {
 double a;
 double b;
};
typedef std::list<Element> ElementList;

class DoStuff {
public:
  DoStuff();

  void removeDuplicates(ElementList & incList) const {
     for(ElementList::reverse_iterator stackIter = incList.rbegin(); stackIter != incList.rend(); ++stackIter) {
        bool uniqueElement = true;
        for(ElementList::reverse_iterator searchIter = stackIter+1; searchIter != incList.rend() && uniqueElement; ++searchIter) {
            //Check stuff and make uniqueElement = true;
         } 
     }
  }
};

int main() {
  std::list<Element> fullList;

  DoStuff foo;
  foo.removeDuplicates(fullList);
}

I get a compile error on the searchIter creation... why...

This works, but its stupid to read:

ElementList::reverse_iterator searchIter = stackIter;
searchIter++;
for( ; searchIter != incList.rend() && uniqueElement; ++searchIter) {

}

Error below:

In file included from /usr/local/include/c++/6.1.0/bits/stl_algobase.h:67:0,
                 from /usr/local/include/c++/6.1.0/list:60,
                 from main.cpp:1:
/usr/local/include/c++/6.1.0/bits/stl_iterator.h: In instantiation of 'std::reverse_iterator<_Iterator> std::reverse_iterator<_Iterator>::operator+(std::reverse_iterator<_Iterator>::difference_type) const [with _Iterator = std::_List_iterator<Element>; std::reverse_iterator<_Iterator>::difference_type = long int]':
main.cpp:16:66:   required from here
/usr/local/include/c++/6.1.0/bits/stl_iterator.h:233:41: error: no match for 'operator-' (operand types are 'const std::_List_iterator<Element>' and 'std::reverse_iterator<std::_List_iterator<Element> >::difference_type {aka long int}')
       { return reverse_iterator(current - __n); }

The syntax it + n for some iterator it and integer n requires the iterator to be a "random access iterator". List iterators do not fulfill that requirement.

To get around the "stupid to read" issue, you can use std::next :

for(ElementList::reverse_iterator searchIter = std::next(stackIter); ...

Or, with less typing:

for(auto searchIter = std::next(stackIter); ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM