使用错误类型的 begin() 重载的 C++ 映射自定义迭代器

C++ map custom iterator using the wrong type of begin() overload

对于学校练习,我正在尝试使用红黑树方法重新编码地图 STL 容器,但在调用它们时遇到了使用 which begin() 重载的问题。 出于测试目的,我尝试使用以下函数显示我的地图的内容:

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 << "] | ";
}

但是我得到一个错误,告诉我没有从迭代器类型到 const_iterator 类型的可行转换。这意味着当循环调用 begin() 时,它调用非 const begin() 函数,returns 迭代器而不是 const_iterator.My 实现如下:

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

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

_tree.begin() 函数 returns 节点到树中的头元素, 我这样在我的地图 class 中定义迭代器:

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

我做错了什么?

正如 @n.1.8e9-where's-my-sharem 所说:

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.

我缺少的是 const_iterator class 中的构造函数,它能够复制迭代器的内容!