常量映射迭代器不会设置为 mymap.begin()

Constant map iterator won't set to mymap.begin()

本文关键字:mymap begin 设置 映射 迭代器 常量      更新时间:2023-10-16
map<string,Shopable*>::iterator it = mymap.begin();

迭代器看起来是常量,但是items.begin()没有返回常量迭代器。或者,这就是我认为的因为鼠标悬停错误类似于:

"No conversion from 'std::Tree_const_iterator<...> to std::Tree_iterator<...> exists'".

为什么?

使用const_iterator作为:

map<string,Shopable*>::const_iterator it = mymap.begin();

从错误中可以看出,mymap.begin()返回const_iterator。这是因为mymapconst在函数中,你已经写了这个,像下面的东西:

void f(const std::map<int,int> & m)
{    //^^^^^ note this
      std::map<int,int>::const_iterator it = m.begin(); //m is const in f()
                       //^^^^^ note this
}
void g(std::map<int,int> & m)
{
      std::map<int,int>::iterator it = m.begin(); //m is non-const in g()
}

即,const容器(无论其std::mapstd::vector等)返回const_iterator,非const容器返回iterator

每个容器有begin()end()的重载函数。因此,const容器调用重载的begin()返回const_iterator,而非const容器调用另一个重载的begin()返回iterator。对于end()重载函数也是如此。

问题是上面代码中的mymap是一个常量映射,而不是一个可变映射(也许它是类的成员,而代码在常量成员函数内?)。因此,对mymap.begin()的调用将拾取返回const_iterator的重载,而不是返回iterator的重载。

如果不需要通过迭代器改变容器,则使用const_iterator。如果您打算修改map,请确保在循环中使用非const对象(可能成员函数(如果是这种情况)不应该是const?)