3

vector::iterator から int へのマップは定義できるのに、list::iterator から int へのマップは定義できないのはなぜですか?

#include <vector>
#include <list>
#include <map>
#include <algorithm>
using namespace std;


int main()
{
    int ia[] = {1,2,3,4,5,6,7,8,9,0};

    vector<int> v(begin(ia), end(ia));
    auto it1 = find(begin(v), end(v), 4);
    map< vector<int>::const_iterator, int > m1;
    m1.insert(map<vector<int>::const_iterator, int>::value_type(it1,*it1));

    list<int> l(begin(ia), end(ia));
    auto it2 = find(begin(l), end(l),5);
    map< list<int>::const_iterator, int> m2;
    m2.insert(map<list<int>::const_iterator, int>::value_type(it2,*it2)); //doesn't compile

}

エラー 1 エラー C2678: バイナリ '<' : 型 'const std::_List_const_iterator<_Mylist>' の左側のオペランドを取る演算子が見つかりません (または、受け入れ可能な変換がありません)

4

3 に答える 3

4

You cannot compare iterators from std::list<T> for any T. Indeed, std::vector<T>::iterator is only comparable if both iterators in question come from the same vector.

于 2012-10-06T20:00:20.973 に答える
0

std::listイテレータを比較できない理由は、それが非常に非効率的であるということです.他の要素がそれの後にないことを見つけるためだけに、それらの1つからおそらくリスト全体の最後まで歩く必要があります. これはO(N)複雑であり、 のような単純な操作には望ましくありません<

何のために必要なのかわからないので、代替品を提案することはできません。の要素のアドレスstd::listは安定しているため、アドレスを のキーとして使用できますmap。しかし、これがどのように役立つかわかりません。

于 2012-10-06T20:06:32.543 に答える