gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:51:13 25 4
gpt4 key购买 nike

给定以下类:

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);
};

如何为我的类定义iteratorconst_iterator? (我想使用 vector 的迭代器来实现 class iteratorclass 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 循环的更多说明,请参见此处:How to make my custom type to work with "range-based for loops"?

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

关于c++ - 当我在类中使用 std::vector 作为字段时,如何在类中定义 iterator 和 const_iterator?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51148797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com