如何在课堂上实现标准迭代器 [英] How to implement standard iterators in class

查看:69
本文介绍了如何在课堂上实现标准迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些类,这些类通常使用标准容器作为基础字段。例如,我有一个类

I have classes which are usually using standard containers as underlying fields. For example, I have a class

template <typename T>
class Vec_3D
{
public:
    /* ... */
    std::array<T, 3> vec;
    /* ... */
};

其中只有一个变量 vec 其余只是使用向量时需要的功能。我希望能够使用基于范围的for循环,例如

which has only one variable vec and the rest are just functions I need when working with vectors. I want to be able to use range-based for loop such as

Vec_3D<double> vec;
for (double val : vec) {/*...*/}

其中应该在 std :: array< double,3> 上进行迭代。

which should obviusly iterate over std::array<double, 3>.

如何在我的课程应该依次调用 std :: array< T,3> 的迭代器?

How to implement iterators in my class which should in turn call iterators of std::array<T, 3>?

我从此问题开始,并试图定义我班上的迭代器为

I started with this question and tried to define iterators in my class as

typedef std::iterator<std::random_access_iterator_tag, T, ptrdiff_t, T*, T&> iterator;
typedef std::iterator<std::random_access_iterator_tag, const T, ptrdiff_t, const T*, const T&> const_iterator;

inline iterator begin() noexcept { return vec.begin(); }
inline const_iterator cbegin() const noexcept { return vec.cbegin(); }
inline iterator end() noexcept { return vec.end(); }
inline const_iterator cend() const noexcept { return vec.end(); }

但出现编译错误

error: no match for ‘operator!=’ (operand types are ‘Vec_3D<double>::iterator {aka std::iterator<std::random_access_iterator_tag, double, long int, double*, double&>}’ and ‘Vec_3D<double>::iterator {aka std::iterator<std::random_access_iterator_tag, double, long int, double*, double&>}’)

operator ++,运算符*

推荐答案

基于范围的for循环仅要求您的类具有 begin() end ()方法(或 std :: begin() std :: end())返回迭代器。不管这些迭代器来自哪里。因此,最简单的解决方案是仅使用数组自己的迭代器,而不是尝试定义自己的迭代器,例如:

A range-based for loop only requires that your class have begin() and end() methods (or overloads of std::begin() and std::end()) that return iterators. It doesn't care where those iterators come from. So, the simplest solution is to just use the array's own iterators instead of trying to define your own, eg:

template <typename T>
class Vec_3D
{
public:
    typedef typename std::array<T, 3> array_type;
    typedef typename array_type::iterator iterator;
    typedef typename array_type::const_iterator const_iterator;
    // or:
    // using array_type = std::array<T, 3>;
    // using iterator = array_type::iterator;
    // using const_iterator = array_type::const_iterator;
    ...

    inline iterator begin() noexcept { return vec.begin(); }
    inline const_iterator cbegin() const noexcept { return vec.cbegin(); }
    inline iterator end() noexcept { return vec.end(); }
    inline const_iterator cend() const noexcept { return vec.cend(); }
    ...

private:
    array_type vec;
};

这篇关于如何在课堂上实现标准迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆