samedi 2 janvier 2021

Multiple custom iterators for same container

I have a created a dynamic container for storing bytes as uint8_t and have implemented an iterator class inside the container class. The iterator traverses through the bytes as expected. But these bytes are formatted with headers so I want to implement another iterator to skip through the byte array based on byte headers. Is it possible to have both iterator classes run when used with for(auto &x: container) based on which class is declared first? or is there some other way to do this?

Current iterator and container

class container {

public:

    container() : s(0), c(2), data(new uint8_t[2]) {};
    container(size_t reserve) : s(0), c(reserve + 1), data(new uint8_t[reserve + 1]) {};
    ~container();

    // container insert, operators etc...

    // iterator class

    class Iterator {

    public:

        uint8_t* ptr;

        using iterator_category = std::forward_iterator_tag;
        using difference_type = std::ptrdiff_t;
        using value_type = uint8_t;
        using pointer = uint8_t*;
        using reference = uint8_t&;

        Iterator(pointer m_ptr) : ptr(m_ptr) { std::cout << "In iterator 1" << std::endl; }
        reference operator*() const;
        pointer operator->();
        Iterator& operator++();
        Iterator operator++(int);
        Iterator& operator+=(int const& lhs);
        Iterator operator+(int const& lhs);
        friend bool operator== (const Iterator& a, const Iterator& b);
        friend bool operator!= (const Iterator& a, const Iterator& b);

    };

    Iterator begin() const;
    Iterator end() const;

private:

    uint8_t* data;
    size_t s;
    size_t c;

};

Aucun commentaire:

Enregistrer un commentaire