【发布时间】: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& ccont = cont;稍后再使用ccont。 -
任何迭代器都应该可以转换为相应的 const_iterator。您可以将转换运算符添加到迭代器类,或将转换构造函数添加到 const_iterator 类。
标签: c++ dictionary stl overloading