linux - C++ map adds new element -



linux - C++ map adds new element -

i have basic query in c++ maps,

map<char,string> mymap; mymap['a']="an element"; mymap['b']="another element"; mymap['c']=mymap['b']; cout << "mymap['a'] " << mymap['a'] << endl; cout << "mymap['b'] " << mymap['b'] << endl; cout << "mymap['c'] " << mymap['c'] << endl; cout << "mymap['d'] " << mymap['d'] << endl;

when seek access mymap['d'], default value because operator inserts new element in map key , initialized default value, though accessed retrieve value. next time when utilize iterator, see null value key 'd'. there way restrict map inserting default values.

you should utilize map.find instead of operator [] if not want default insertion.

map::find

iterator find ( const key_type& x ); const_iterator find ( const key_type& x ) const;

searches container element x key , returns iterator if found, otherwise returns iterator map::end (the element past end of container)

c++ linux

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -