user997112
user997112

Reputation: 30675

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.

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

Upvotes: 1

Views: 283

Answers (3)

Mr.C64
Mr.C64

Reputation: 43044

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.

Upvotes: 1

RomMer
RomMer

Reputation: 113

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

Upvotes: 0

Benjamin Lindley
Benjamin Lindley

Reputation: 103761

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.

Upvotes: 5

Related Questions