【问题标题】:C++ map custom iterator using the wrong type of begin() overloadC++ 使用错误类型的 begin() 重载映射自定义迭代器
【发布时间】:2021-12-09 09:15:58
【问题描述】:

对于学校练习,我正在尝试使用 Red-Black Tree 方法重新编码 map 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()的时候,调用的是返回iterator而不是const_iterator的非const begin()函数。我的实现如下:

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

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

_tree.begin() 函数将节点返回到树中的头元素, 我以这种方式在我的地图类中定义迭代器:

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

我做错了什么?

【问题讨论】:

  • 通常你会使用const_iterator cbegin() const;,即在方法名称前加上c。这就是 STL 的作用。
  • 我不得不使用 c++98 库进行编码,所以我无法编写 cbegin()
  • 如果你不能使用不同的方法名,那么你可以先将容器转换为 const 吗?
  • T const&amp; ccont = cont; 稍后再使用ccont
  • 任何迭代器都应该可以转换为相应的 const_iterator。您可以将转换运算符添加到迭代器类,或将转换构造函数添加到 const_iterator 类。

标签: c++ dictionary stl overloading


【解决方案1】:

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

任何迭代器都应该可以转换为相应的 const_iterator。 您可以将转换运算符添加到您的迭代器类,或 将构造函数转换为 const_iterator 类。

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

【讨论】:

  • 您会在回答中引用解决方案吗?
猜你喜欢
  • 1970-01-01
  • 2019-01-25
  • 2012-02-03
  • 1970-01-01
  • 2015-05-19
  • 2021-04-15
  • 2011-07-31
  • 2017-06-20
  • 2016-03-30
相关资源
最近更新 更多