How to implement standard iterators in class

前端 未结 3 1556
温柔的废话
温柔的废话 2021-02-06 04:40

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

template 
class Vec_3D
{
public:
          


        
3条回答
  •  孤独总比滥情好
    2021-02-06 05:37

    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 
    class Vec_3D
    {
    public:
        typedef typename std::array array_type;
        typedef typename array_type::iterator iterator;
        typedef typename array_type::const_iterator const_iterator;
        // or:
        // using array_type = std::array;
        // 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;
    };
    

提交回复
热议问题