c++ - 比较迭代器和 const_iterators

标签 c++ stl iterator constants stdmap

我有一个方法可以找到 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/

相关文章:

c++ - 为什么我在编译期间收到语法错误?

c++ - 使用 LLVM 检测 C/C++ 代码

与 STL 相关的 C++ ABI 问题

python-3.x - 为列表列表中的每个列表将字符串插入索引[0]。 Python

c++ - 遍历 map 会使应用程序崩溃

c++ - 读取字符串作为命令行参数 C++

c++ - 在类定义内部和外部定义成员函数之间有区别吗?

c++ - 使用 STL 队列的循环队列?

c++ - 为什么不能 map::find 指向 const 的指针?

c++ - 为什么会出现这个段错误?