SORU
4 Kasım 2008, Salı


C göster erişimi atar elemeleri (inş)

Aşağıdaki kodu operator[] yöntem const olarak göster elemeleri geçen atar diyor ki:

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

Harita erişim oluşur mümkün ayırma yüzünden mi? Harita erişir hiçbir fonksiyonları sabit ilan edilebilir mi?

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

CEVAP
4 Kasım 2008, Salı


std::map's operator [] is not declared as const, and cannot be due to its behavior:

T& operator[] (sabit) Anahtar& anahtar

Döner bir anahtar için eşdeğer eşlenen değer bir başvuru, eğer böyle bir anahtar zaten mevcut değilse, ekleme yapmak.

Sonuç olarak, fonksiyon const, ilan edilemez ve operator[] bu haritayı kullanın.

23* *fonksiyon haritası değiştirmeden bir anahtar aramak için izin verir.

find() std::pair bir anahtarı (.first) hem de değeri içeren (.second) iterator const_iterator döndürür.

C de std::map at() kullanabilirsiniz 11,. Eğer eleman yok diye fonksiyonu std::out_of_range özel operator [] aksine atar.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • colacas

    colacas

    29 EKİM 2006
  • jcortes187

    jcortes187

    24 Mart 2006
  • Kap Slap

    Kap Slap

    8 Mart 2010