简体   繁体   English

比较迭代器和const_iterators

[英]Comparing iterator and const_iterators

I have a method which finds the particular position in a map and 'returns' this via an iterator reference: 我有一个方法可以找到地图中的特定位置,并通过迭代器引用“返回”该位置:

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;
}

I am getting a compiler error because std::upper_bound() is returning an std::const_iterator and comparing this with an std::iterator . 我收到一个编译器错误,因为std::upper_bound()返回一个std::const_iterator并将其与std::iterator进行比较。

Should I 'cast' the return value of upper_bound() to be non-const? 我应该“铸造” upper_bound()的返回值是非常量吗?

No, you should not cast the return value of upper_bound . 不,您不应该upper_bound的返回值。 You should remove the const qualifier on the function. 您应该删除const上的const限定词。 The function is providing non-const access to an element of the map (via the out parameter), so it should not be const. 该函数提供对地图元素的非常量访问(通过out参数),因此不应为const。

 bool Func(const int searchKey, MyMap::iterator& iter) const { iter = _map.upper_bound(searchKey); // Compiler error: comparing non-const iterator and const iterator 

This method is marked const , but you are returning a position in the _map using a non - const iterator (the iter parameter), giving to the caller non -const access to the map's elements, thus violating the const method specification. 该方法被标记为const ,但是您将使用 const迭代器( iter参数)在_map中返回位置,从而使调用者对地图元素具有 const访问权限,从而违反了const方法的规范。

Either remove const from Func declaration, or return a MyMap::const_iterator& , depending on what kind of access to the map's elements you want to give to the caller. Func声明中删除const ,或返回MyMap::const_iterator& ,具体取决于您希望给予调用者对地图元素的哪种访问方式。

Or you may write two overloads for Func : a const one and a non- const one, returning a MyMap::const_iterator and MyMap::iterator respectively. 或者,您可以为Func写两个重载:一个const重载和一个非const重载,分别返回MyMap::const_iteratorMyMap::iterator

is your map const qualified ? 您的地图const是否合格?

if your map is const-qualified, std::map::upper_bound will return a const iterator, if it's not it should return an iterator 如果您的地图是const限定符,则std :: map :: upper_bound将返回const迭代器,如果不是,则应返回一个迭代器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM