c++ - std::map check if a map has been assigned a non-default value? -


lets have complex map defined as

std::map<int, std::pair< vector<int>, float> > complex_map;   

let assume initialized map as

for (int k=0;k<5;k++) {     std::pair< vector<int>, float> complex_map_child;     complex_map[k]=complex_map_child; } 

next, populate entries of map:

float test_1 = .7888; vector<int> test_2; test_2.push_back(1); test_2.push_back(2); complex_map[1].first = test_2; complex_map[1].second = test_1; 

so corresponding key value 1 of complex_map, have pair of values corresponding test_1 , test_2.

now how check if have explicitly added values map? i.e in example how havent explicitly filled complex_map[0]?

looks using std::map::operator[] improperly , try go on - getting object this:

auto &complex_value = complex_map[0]; 

and try check if inserted before or implicitly created std::map::operator[].

just not use std::map::operator[] access elements. use when need set value in map.

so proper solution use different methods:

// want check if key 0 there if( complex_map.count( 0 ) ) {      ... }  // want access element key 0 if there auto = complex_map.find( 0 ); if( != complex_map.end() ) {     auto &complex_value = it->second;     ... } 

and on. know writing complex_map[0] shorter creating problem trying solve convoluted way.


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -