反向迭代算术

时间:2016-06-30 17:20:33

标签: c++ stl

所有,我正在尝试在列表中的元素之间进行O(n ^ 2)比较,所以我使用的是反向迭代器。

代码如下

#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);
}

我在searchIter创建时遇到编译错误......为什么......

这有效,但读起来很愚蠢:

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

}

以下错误:

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); }

1 个答案:

答案 0 :(得分:5)

某些迭代器it + n和整数it的语法n要求迭代器是“随机访问迭代器”。列表迭代器不满足该要求。

要解决“愚蠢阅读”问题,您可以使用std::next

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

或者,打字更少:

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