常量映射迭代器不会设置为 mymap.begin()
Constant map iterator won't set to mymap.begin()
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
。这是因为mymap
是const
在函数中,你已经写了这个,像下面的东西:
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::map
、std::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?)
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 调用'begin(int [n])'没有匹配函数
- 为constchar*定义std::begin合法吗
- constexpr begin of a std::array
- remove(str.begin(), str.end(), );无法正常工作(我正在使用视觉工作室 2012)
- 了解向量中的 .begin 和 .end
- 混淆 Begin() 方法作为参数
- std::ranges::begin 和 std::begin 有什么区别?
- C++ const char with .begin() and .end()
- 有没有函数可以在擦除 c++ 中获取 deque.begin() 的 int 值?
- 为什么 string::begin() 在即时窗口中输出整个字符串
- 如果没有重新散列,为什么 unordered_set::begin() 会改变?
- 为什么 std::find( s.begin(), s.end(), val ) 比集合 s 的 s.find(val) 慢 1000 倍<int>?
- begin() 在 C++17 年被制作为 constexpr 但在 C++14 年成为 cbegin() 吗?
- 如何使用vector.begin()和vector.end()遍历矩阵?
- 递减 std::vector::begin 是否未定义,即使它从未被使用过?
- std::begin-类型特征中未考虑用户定义的重载
- 当从成员类调用封装的std::begin时,程序崩溃
- 常量映射迭代器不会设置为 mymap.begin()