[英]How do I convert iterator to const_iterator in my custom list iterator class?
[英]How can I define iterator and const_iterator in my class while I uses std::vector as field in my class?
鑒於以下課程:
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);
};
如何為我的類定義iterator
和const_iterator
? ( 我想使用向量的迭代器來實現class iterator
和class const_iterator
)。
我希望(例如)支持這樣的事情:
A a(5);
for(A<int>::iterator it = a.begin() ; it != a.end() ; it++) { /* .. */ }
您可以在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(); }
};
或者在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(); }
};
然后你可以都支持基於迭代器的迭代:
A<int> a(5);
for(A<int>::iterator it = a.begin() ; it != a.end() ; it++) { /* .. */
}
基於范圍的for循環:
A a(5);
for(auto v : a) { /* .. */
}
有關如何支持基於范圍的for循環的進一步說明,請參見: 如何使我的自定義類型與“基於范圍的for循環”一起使用?
(感謝@JohnML的編輯建議,使得答案符合c ++ 11!)
只需將vector的現有迭代器類型解壓縮到您自己的類中:
template<class T>
class A {
...
public:
typedef vector<T>::iterator iterator;
typedef vector<T>::const_iterator const_iterator;
...
};
要么
template<class T>
class A {
...
public:
using iterator = typename vector<T>::iterator;
using const_iterator = typename vector<T>::const_iterator;
...
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.