Home > Software engineering >  C map custom iterator using the wrong type of begin() overload
C map custom iterator using the wrong type of begin() overload

Time:10-26

For a school exercise I'm trying to recode the map STL container using Red-Black Tree method and I'm having an issue with the use of which begin() overload when I call them. For testing purpose I'm trying to show the content of my map with the following function:

template <typename T>
inline void printMapContainer(T& cont)
{
    for (typename T::const_iterator it = cont.begin(); it != cont.end();   it)
        std::cout << "[" << it->first << "][" << it->second << "] | ";
}

But I get an error that tells me that there is no viable conversion from iterator type to const_iterator type. It means that when the loop calls begin(), it calls the non const begin() function that returns iterator instead of const_iterator.My implementation is the following:

        iterator                    begin()
        {
            return (iterator(this->_tree.begin()));
        };

        const_iterator              begin()                     const
        {
            return (const_iterator(this->_tree.begin()));
        };

The _tree.begin() function returns the node to the head element in the tree, and I define the iterator in my map class this way:

typedef typename    ft::rb_tree<value_type, Compare>::iterator      iterator;
typedef typename    ft::rb_tree<value_type, Compare>::const_iterator    const_iterator;

What am I doing wrong?

CodePudding user response:

As @n.1.8e9-where's-my-sharem said:

Any iterator should be convertible to a corresponding const_iterator. You may add either a conversion operator to your iterator class, or a conversion constructor to your const_iterator class.

what I was missing is a constructor in my const_iterator class that would be able to copy the content of an iterator!

  • Related