// base define std::map <std::string, std::string> sColleagueMap; // 插入元素 sColleagueMap.insert( std::pair<std::string, std::string>( "rao" , "haijun" ) ); sColleagueMap.insert( std::pair<std::string, std::string>( "zhao" , "jingjing" ) ); sColleagueMap.insert( std::pair<std::string, std::string>( "fan" , "junjie" ) ); // 访问指定元素 std::cout<<sColleagueMap.at( "rao" )<<std::endl; // 判断map中是否包含某个元素 std::cout<<sColleagueMap.count( "rao" )<<std::endl; // 查找map中是否包含某个元素 auto findIt = sColleagueMap.find( "fan" ); if (findIt != sColleagueMap.end() ){ std::cout<< "find the element:" <<findIt->first<<findIt->second<<std::endl; } // 遍历元素(不允许修改) 从前到后 C++11标准 auto sCollItConst = sColleagueMap.cbegin(); for (; sCollItConst!=sColleagueMap.cend(); ++sCollItConst){ std::cout<<sCollItConst->first<<sCollItConst->second<<std::endl; } // 遍历元素(不允许修改) 从后到前 C++11标准 auto sCollItConstr = sColleagueMap.crbegin(); for (; sCollItConstr!=sColleagueMap.crend(); ++sCollItConstr){ std::cout<<sCollItConstr->first<<sCollItConstr->second<<std::endl; } // 遍历元素(可以修改)从前到后 std::map<std::string, std::string>::iterator sCollIt = sColleagueMap.begin(); for (; sCollIt!=sColleagueMap.end(); ++sCollIt){ if (sCollIt->first == "rao" ){ sCollIt->second = "yuke" ; } std::cout<<sCollIt->first<<sCollIt->second<<std::endl; } // 遍历元素(可以修改)从后到前 std::map<std::string, std::string>::reverse_iterator sCollItR = sColleagueMap.rbegin(); for (; sCollItR!=sColleagueMap.rend(); ++sCollItR){ if (sCollItR->first == "rao" ){ sCollItR->second = "zhihao" ; } std::cout<<sCollItR->first<<sCollItR->second<<std::endl; } // 清空所有元素 sColleagueMap.clear(); std::cout<<sColleagueMap.size()<<std::endl; // 判断map的所能hold到的最大element个数 std::cout<< "max:" <<sColleagueMap.max_size()<<std::endl; char *pNew = new char [1024*1024*1024]; if (!pNew){ std::cout<< "malloc memory error!" <<std::endl; } std::cout<< "max:" <<sColleagueMap.max_size()<<std::endl; delete [] pNew; // 判断是否为空 std::cout<<sColleagueMap.empty()<<std::endl; |