[STL]对std::map的插入和查询操作

When you use the std::map data type, please note:

 Method1

std::map < int , CString >  testMap;
testMap[
0 =  _T(“first”);
testMap[
0 =  _T(“second”); // it is OK, the value will be overwrite to “second”;

 

Method2

typedef std::map  < int , CString > ::value_type valType;
testMap.insert(valType(
0 , _T(“first”));
testMap.insert(valType(
0 , _T(“second”));  // it is faild, the value is still “first”

So in the method2, you have to delete the value with the same key before insert another value.

e.g.:

std::map  < int , CString > ::integrator it  =  testMap.find( 0 );
if  ( it  !=  testMap.end(); it ++  )
      testMap.erase(
0 );

What’s more, when you get a value by the array method(method1), If the specified key doesn’t exist in map, the key will be inserted automatically with a empty value. So make sure use testMap.find(key) to get any value in map rather than the array visite method.

e.g.:

// the key “1” doesn’t exist, it will be inserted and return  a empty string here.
CString str  =  testMap[ 1 ];

你可能感兴趣的:(delete,insert)