Comparing iterator and const_iterators

285 views Asked by At

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.

Should I 'cast' the return value of upper_bound() to be non-const?

3

There are 3 answers

2
Benjamin Lindley On

No, you should not cast the return value of upper_bound. You should remove the const qualifier on the function. The function is providing non-const access to an element of the map (via the out parameter), so it should not be const.

0
RomMer On

is your map const qualified ?

if your map is const-qualified, std::map::upper_bound will return a const iterator, if it's not it should return an iterator

0
Mr.C64 On
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.

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.

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.