繁体   English   中英

const_iterator 到迭代器 C++ 错误

[英]const_iterator to iterator C++ Error

我正在尝试使用以下代码块迭代map对象:

for(map<int, vector>::iterator table_iter = table.being(); table_iter != table.end(); table_iter++)
{
    ...
}

我不断收到错误告诉我:

请求从 const_iterator 到非标量类型迭代器的转换

而且我似乎无法确定为什么迭代器会是const与非const ,或者如何处理这个问题。

使用map<int, vector>::const_iterator而不是由map::begin返回。

听起来table是一个const对象或引用,在这种情况下begin返回一个const_iterator 将您的 for 循环更改为:

// typedefs make for an easier live, note const_iterator
typedef map<int, vector>::const_iterator iter_type;
for(iter_type table_iter = table.begin(); table_iter != table.end(); table_iter++)
{
    ...
}

嗯,你的问题得到了部分回答。

“而且我似乎无法确定为什么迭代器会是常量与非常量,或者如何处理这个。” 正如其他人回答的那样,如果您的表被定义为常量,则需要定义一个常量迭代器。 缺少的是,如果函数被定义为 const,则迭代器也应该是 const。

我认为 const 函数是您的问题,而不是 const 表。

我猜表是一个常量&。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM