How to realize the end on the map?

I am implementing a map for excersise, and I am at the point where I have to iterate over (do and work), but the problem is that I don’t know how to implement the last element (presumably an empty link). I thought that I would attach some kind of special link (a descendant of the base link), which would then be attached to the last element, and thus I could find out that I was in the real last element or not. I wonder what your opinion about this idea will be, and perhaps you will hear from you about more traditional and regularly used techniques for this.

+3
source share
3 answers

If your iterator is not bidirectional, you don't need an end to point to anything (just use NULL in this case). end()you only need to have real value in the case of a bidirectional iterator, because in this case you will need to move back from end()the top of the list.

The GNU C ++ library (what you get if you use std::mapwith GCC / g ++) implements end()as a pointer to the root of the node tree. Thus, if it is used in a bidirectional iterator, you can access the root file of the node to find the largest node in the tree (this is the node immediately before end()).

Change the explanation of an empty tree

node ( , node). , node node ( end()). begin() , end().

, - :

template<class T> struct node_t {
    T data;
    node_t *left;
    node_t *right;
};


template<class T> class map {
    private:
        node_t root;
    public:
        // ...
        iterator begin() { return iterator(root.left); }
        iterator end() { return iterator(&root); }
}
+3

end: node (.. NULL).

NULL , , --end().

GCC , node map. , . , , . , , ++, .

+3

Use a dummy node for this.

0
source

Source: https://habr.com/ru/post/1759747/


All Articles