常量映射迭代器不会设置为 mymap.begin()
map<string,Shopable*>::iterator it = mymap.begin();
迭代器看起来是常量,但 items.begin()
不返回常量迭代器。或者,这就是我的想法,因为鼠标悬停错误类似于:
"No conversion from 'std::Tree_const_iterator<...> to std::Tree_iterator<...> exists'".
为什么?
map<string,Shopable*>::iterator it = mymap.begin();
The iterator appears to be constant, but items.begin()
doesn't return a constant iterator. Or, that's what I think because the mouseover error is something like:
"No conversion from 'std::Tree_const_iterator<...> to std::Tree_iterator<...> exists'".
Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
const_iterator
as :从错误中可以清楚地看出,
mymap.begin()
返回const_iterator
。这是因为mymap
在您编写此代码的函数中是const
,如下所示:即
const
容器(无论其 < code>std::map、std::vector
等)返回const_iterator
,非常量容器返回iterator
。每个容器都有重载函数
begin()
和end()
。因此,const
容器调用重载的begin()
,它返回const_iterator
,非常量容器调用另一个重载的begin()
code> 返回迭代器
。对于end()
重载函数也是如此。Use
const_iterator
as :From the error, its clear that
mymap.begin()
returnsconst_iterator
. That is becausemymap
isconst
in the function where you've written this, something like following:That is,
const
container (whether itsstd::map
,std::vector
etc) returnsconst_iterator
and non-const container returnsiterator
.Every container has overloaded functions of
begin()
andend()
. Soconst
container invokes the overloadedbegin()
which returnsconst_iterator
and non-const container invokes the other overloadedbegin()
which returnsiterator
. And same forend()
overloaded functions.问题是上面代码中的 mymap 是常量映射,而不是可变映射(也许它是类的成员,并且该代码位于常量成员函数内部?)。因此,对
mymap.begin()
的调用将获取返回const_iterator
的重载,而不是返回iterator
的重载。如果不需要通过迭代器更改容器,请使用const_iterator。如果您打算修改映射,请确保在循环中使用非常量对象(也许成员函数(如果是这种情况)不应该是 const?)
The problem is that
mymap
in the code above is a constant map, not a mutable map (maybe it is a member of a class and that code is inside constant member function?). Thus the call tomymap.begin()
will pichup the overload that returns aconst_iterator
instead of the overload that returns aniterator
.If you do not need to change the container through the iterator, use
const_iterator
. If you intend on modifying the map, make sure that you are using a non-const object for the loop (maybe the member function (if that is the case) should not be const?)