简体   繁体   English

反向迭代器算法

[英]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. 全部,我试图反向执行列表中元素之间的O(n ^ 2)比较,所以我正在使用反向迭代器。

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... 我在searchIter创建时遇到编译错误...为什么...

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". 语法it + n一些迭代it和整数n要求迭代器是一个“随机访问迭代器”。 List iterators do not fulfill that requirement. 列表迭代器不满足该要求。

To get around the "stupid to read" issue, you can use std::next : 要解决“阅读笨拙”的问题,可以使用std::next

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

Or, with less typing: 或者,输入更少:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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