11 Mart 2021 Perşembe

std::map [] operator

Giriş
Bu operator eğer aranan key yoksa default constructor kullanarak bir value ile doldurur. Açıklaması şöyle
T& operator[](const key_type& x);
1 Effects: If there is no key equivalent to x in the map, inserts value_type(x, T()) into the map.
Eğer value tipinin default constructor metodu yoksa hata alırız. Aşağıdaki kod derlenmez!
std::map< int, std::reference_wrapper< foo > > my_map;
foo a;
my_map[ 0 ] = std::ref( a );
Örnek - primitive tip
Şöyle yaparız
std::map<std::string,std::size_t> counters;
//...
counters[key]++;
Açıklaması şöyle
++counters[key]; is completely valid. std::map::operator[] inserts a value-initialized element if the key does not exist in the map. This is the idiomatic way of doing what you explained.

Hiç yorum yok:

Yorum Gönder