Accessing Map element using [] operator adds new element if key does not exist.

  • Thread starter Thread starter sgrm123
  • Start date Start date
S

sgrm123

Guest
Hi,

Accessing Map element using [] operator adds new element with default value if key does not exist. How to avoid that?

// accessing mapped values
#include <iostream>
#include <map>
#include <string>

int main ()
{
std::map<char,std::string> mymap;

mymap['a']="an element";
mymap['b']="another element";
mymap['c']=mymap['b'];

std::cout << "mymap['a'] is " << mymap['a'] << '\n';
std::cout << "mymap['b'] is " << mymap['b'] << '\n';
std::cout << "mymap['c'] is " << mymap['c'] << '\n';
std::cout << "mymap['d'] is " << mymap['d'] << '\n';

std::cout << "mymap now contains " << mymap.size() << " elements.\n";

return 0;
}

access (to element <tt style="color:#000000;font-family:verdana,arial,helvetica,sans-serif;font-size:12px;font-style:normal;font-variant:normal;font-weight:400;letter-spacing:normal;orphans:2;text-align:left;text-decoration:none;text-indent:0px;text-transform:none;-webkit-text-stroke-width:0px;white-space:normal;word-spacing:0px;">'d'</tt>) inserts a new element in the map with that key and initialized to its default value (an empty string) .How to avoid it?

Continue reading...
 
Back
Top