我有一个方法可以找到 map 中的特定位置并通过迭代器引用“返回”它:
bool Func(const int searchKey, MyMap::iterator& iter) const {
iter = _map.upper_bound(searchKey); // Compiler error: comparing non-const iterator and const iterator
const bool found = iter != _map.begin();
if(something){
--_map;
return true;
}
return false;
}
我收到一个编译器错误,因为 std::upper_bound()
正在返回一个 std::const_iterator
并将其与一个 std::iterator
.
我应该将 upper_bound()
的返回值“转换”为非常量吗?
最佳答案
不,你不应该强制转换 upper_bound
的返回值。您应该删除函数上的 const
限定符。该函数提供对 map 元素的非常量访问(通过 out 参数),因此它不应该是常量。
关于c++ - 比较迭代器和 const_iterators,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41188446/