当我在类中使用 std::vector 作为字段时,如何在类中定义 iterator 和 const_iterator ?

Sof*_*e_t 5 c++ iterator class vector c++11

给定以下课程:

template<class T>
class A {
    vector<T> arr;
public:
    A(int size);
    A(vector<T> arr);
    int size() const;
    A& operator=(const A& p);

    template<class S>
    friend ostream& operator<<(ostream& os, const A<S>& p);

    template<class S>
    friend bool operator==(const A<S>& p1, const A<S>& p2);   
};
Run Code Online (Sandbox Code Playgroud)

我如何为我的班级定义iterator和?const_iterator我想使用向量的迭代器来实现class iteratorandclass const_iterator)..


我想(例如)支持类似的事情:

A a(5);  
for(A<int>::iterator it = a.begin() ; it != a.end() ; it++) { /* .. */ }
Run Code Online (Sandbox Code Playgroud)

Oli*_*ohn 5

在 C++11 中,您可以简单地执行此操作:

template<class T>
class A {
    vector<T> arr;
public: 

    using iterator = typename vector<T>::iterator;
    using const_iterator = typename vector<T>::const_iterator;

    const_iterator begin() const { return arr.begin(); }
    iterator       begin()       { return arr.begin(); }
    const_iterator end() const { return arr.end(); }
    iterator       end()       { return arr.end(); }
};
Run Code Online (Sandbox Code Playgroud)

或者在 C++14 中:

template<class T>
class A {
    vector<T> arr;
public:
    using iterator = typename vector<T>::iterator;
    using const_iterator = typename vector<T>::const_iterator;

    auto begin() const { return arr.begin(); }
    auto begin()       { return arr.begin(); }
    auto end() const { return arr.end(); }
    auto end()       { return arr.end(); }
};
Run Code Online (Sandbox Code Playgroud)

那么你们都可以支持基于迭代器的迭代:

A<int> a(5);  
for(A<int>::iterator it = a.begin() ; it != a.end() ; it++) { /* .. */ 
}
Run Code Online (Sandbox Code Playgroud)

以及基于范围的 for 循环:

A a(5);  
for(auto v : a) { /* .. */ 
}
Run Code Online (Sandbox Code Playgroud)

有关如何支持基于范围的 for 循环的进一步说明,请参阅此处:How to make my custom type to work with "range-based forloops"?

(感谢@JohnML 的编辑建议,使答案符合 c++11!)