欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

STL-map测试

程序员文章站 2024-02-17 15:21:46
...
#include <map>
#include <iostream>
#include <string>
using namespace std;
int main()
{
   map<string, int> simap; //以string为键值,以int为实值
   simap[string("jjhou")] = 1; //第一对内容是{"jjhou", 1}
   simap[string("jerry")] = 2; //第二对内容是{"jerry", 2}
   simap[string("jason")] = 3; //第二对内容是{"jason", 3}
   simap[string("jimmy")] = 4; //第二对内容是{"jimmy", 4}
   
   pair<string, int> value(string("david"), 5);//pair将两个参数组合在一起
   simap.insert(value);
   
   map<string, int>::iterator simap_iter = simap.begin();             //david 5
   for( ; simap_iter != simap.end(); ++simap_iter)                    //jason 3
       cout << simap_iter->first << ' ' << simap_iter->second << endl;//jerry 2
   //map根据key按字母自动排序                                          //jimmy 4
   int number = simap[string("jjhou")];                               //jjhou 1 
   cout << number << endl; //获取jjhou键值对应的实值:1   
   
   map<string, int>::iterator itel;
   
   itel = simap.find(string("mchen"));
   if(itel == simap.end())
       cout << "mchen not found" << endl; //mchen not found
       
   itel = simap.find(string("jerry"));
   if(itel == simap.end())
       cout << "jerry found" << endl;    //jerry found

   itel->second = 9;                     //可以通过map迭代器修改value,不是key
   int number2 = simap[string("jerry")];
   cout << number2 << endl; //输出9
}                                                    

上一篇: 遍历输出map

下一篇: map排序