Pergunta

O código a seguir diz que passando o mapa como const nas eliminatórias descarta método operator[]:

#include <iostream>
#include <map>
#include <string>

using namespace std;

class MapWrapper {
public:
    const int &get_value(const int &key) const {
        return _map[key];
    }

private:
    map<int, int> _map;
};

int main() {
    MapWrapper mw;
    cout << mw.get_value(42) << endl;
    return 0;
}

Isso é por causa da possível alocação que ocorre no mapa de acesso? Pode nenhuma função com o mapa de acessos ser declarado const?

MapWrapper.cpp:10: error: passing ‘const std::map<int, int, std::less<int>, std::allocator<std::pair<const int, int> > >’ as ‘this’ argument of ‘_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = int, _Tp = int, _Compare = std::less<int>, _Alloc = std::allocator<std::pair<const int, int> >]’ discards qualifiers

Foi útil?

Solução

de std::map operator [] não é declarado como const, e não pode ser devido ao seu comportamento:

T & operador [] (const Key & key)

Retorna uma referência para o valor que é mapeado para um equivalente de tecla de chave, realizando a inserção se essa chave não existir.

Como resultado, a sua função não pode ser declarado const, e usar operator[] do mapa.

de std::map função find() permite-lhe procurar uma chave sem modificar o mapa.

find() retorna um iterator, ou const_iterator a um std::pair contendo ambos a chave (.first) e o valor (.second).

Em C ++ 11, você também pode usar at() para std::map. Se o elemento não existe a função lança uma exceção std::out_of_range, em contraste com operator [].

Outras dicas

Você não pode usar operator[] em um mapa que é const como o método não é const, pois permite que você modifique o mapa (você pode atribuir a _map[key]). Tente usar o método find vez.

Since operator[] does not have a const-qualified overload, it cannot be safely used in a const-qualified function. This is probably because the current overload was built with the goal of both returning and setting key values.

Instead, you can use:

VALUE = map.find(KEY)->second;

or, in C++11, you can use the at() operator:

VALUE = map.at(KEY);

Some newer versions of the GCC headers (4.1 and 4.2 on my machine) have non-standard member functions map::at() which are declared const and throw std::out_of_range if the key is not in the map.

const mapped_type& at(const key_type& __k) const

From a reference in the function's comment, it appears that this has been suggested as a new member function in the standard library.

First, you should not be using symbols beginning with _ because they are reserved to the language implementation/compiler writer. It would be very easy for _map to be a syntax error on someone's compiler, and you would have no one to blame but yourself.

If you want to use an underscore, put it at the end, not the beginning. You probably made this mistake because you saw some Microsoft code doing it. Remember, they write their own compiler, so they may be able to get away with it. Even so, it's a bad idea.

the operator [] not only returns a reference, it actually creates the entry in the map. So you aren't just getting a mapping, if there is none, you are creating one. That's not what you intended.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top