K
K
Karponter2015-12-03 03:36:10
OOP
Karponter, 2015-12-03 03:36:10

Polymorphism and iteration over custom containers. Shall we start?

There is a custom container based on the linked list principle. Linked nodes.
There is a task: to connect to it the iterator.
The struct iterator class I inherit from the bidirectional node iterator.
My idea is to redefine the * and -> operators in such a way that they return not a specific iterable node of the tree, but the data that is stored in the node. In other words - to veil the use of the node structure and completely hide them from external use.
Of course, they don’t allow me to simply redefine the operator, due to a type conflict.

template class MyIterator : std::iterator <std::bidirectional_iterator_tag, MyQueueNode<T>> {};

MyIterator pulls from std::iterator the operators defined in it (* and ->), which return the MyQueueNode type (which is logical, because to track links between nodes, you need to iterate over the nodes themselves and not over the data they store). I need to write operators (* and ->) for MyIterator that will return type T, to which the compiler says "sorry, bro, return type conflict."
If you iterate directly over the data, then how to implement ++ and -- in this case?
Perhaps there is a way to bypass the inheritance of operators, and prescribe new ones, ignoring the parent ones?
And in general, it is interesting to hear ideas about this.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MiiNiPaa, 2015-12-03
@karponter

1) You inherited from std::iterator incorrectly. The second parameter is the type that should be obtained after the dereference. If the * operator returns T, then put T as a parameter.
2)

MyIterator pulls from std::iterator the operators defined in it (* and ->),
What are the specific operators? std::iterator defines several type aliases, that's all.
You need to:
a) Store a pointer to the node in the iterator.
b) The ++ and -- operators move the pointer to the next/previous node
. c) The * and -> operators access the data in the current node.
Something like this:
template <typename T>
struct Node
{
    T data;
    Node* next;
    Node* prev;
};

template <typename T>
class list_iterator : public std::iterator<std::bidirectional_iterator_tag, T> 
{
    private:
    
    Node<T>* current;
    
    public:
    
    list_iterator& operator++()
    {
        current = current->next;
        return *this;
    }
    
    T& operator*()
    {
        return current->data;   
    }
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question