比较iterator和const_iterators

use*_*112 1 c++ iterator stl const stdmap

我有一个方法在地图中找到特定的位置,并通过迭代器引用'返回':

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;
}
Run Code Online (Sandbox Code Playgroud)

我收到编译器错误,因为std::upper_bound()它返回std::const_iterator并将其与a进行比较std::iterator.

我应该'转换'非常量的返回值upper_bound()吗?

Ben*_*ley 5

不,你不应该抛出返回值upper_bound.您应该删除const该函数上的限定符.该函数提供对地图元素的非常量访问(通过out参数),因此它不应该是const.