std :: sort无法识别迭代器类别

时间:2016-03-24 14:36:04

标签: c++ templates c++11 iterator

我的一些矢量迭代器的实现:

class iterator : public std::iterator<std::input_iterator_tag, int> {
    Vector<T> *vector;
    size_t position;

public:
    iterator(Vector<T> *vector_, size_t idx) {...};
    iterator(const iterator &it) {...};
    friend bool operator == (const iterator &a, const iterator &b) {...};
    friend bool operator > (const iterator &a, const iterator &b) {...};
    friend bool operator < (const iterator &a, const iterator &b) {...};
    friend bool operator >= (const iterator &a, const iterator &b) {...};
    friend bool operator <= (const iterator &a, const iterator &b) {...};
    friend bool operator != (const iterator &a, const iterator &b) {...};
    iterator &operator = (const iterator &b) {...};
    T operator * () {...};
    iterator &operator ++ () {...}
    iterator &operator -- () {...}

    std::ptrdiff_t operator - (const iterator &b) const {...}
};

但是出于原因,调用std::sort(vector.begin(), vector.end())会输出no operator +=之类的错误,这表明事件std::sort将我的迭代器视为随机访问。为什么?

1 个答案:

答案 0 :(得分:7)

std::sort需要RandomAccessIterator秒。虽然它可能认识到你给了它不兼容的迭代器,但它仍然无法工作。