2016-06-30 16 views
0

すべて、逆のリストの要素間で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); } 
+0

エラーとは何ですか? – NathanOliver

答えて

5

イテレータitと整数nの構文it + nは、イテレータが「ランダムアクセス反復子」であることが必要です。リストイテレータはその要件を満たしません。

周り問題 "を読んで愚かな" 取得するには、std::nextを使用することができます。

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

あるいは、より少ないタイピングで:

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

悲しいことに、私は[編集された]ためにC++ 11を使用することはできませんが、これは非常に直感的でした。ありがとう! – Constantin

+0

@コンスタンチンあなたは大歓迎です。自分自身を「自分自身」を実装することはあまりにも難しくありません。 :) –