c++ 之 map用法

使用map时,需包含头文件<map.h>
.

一、定义及初始化

//  直接定义
map<char,int> mymap;
mymap['a'] = 10;
mymap['b'] = 60;

//   复制
map<char, int> second(mymap);

//  通过迭代器
map<char, int> third(mymap.begin(),mymap.end());

二、插入元素

map<string, string> mapStudent;

//  用insert函数插入pair
mapStudent.insert(pair<string, string>("r000", "student_zero"));

//  用"array"方式插入
mapStudent["r123"] = "student_first";
mapStudent["r456"] = "student_second";

//  指定位置插入
map<string, string>::iterator it = mapStudent.begin();
mapStudent.insert(it, pair<string, string>("r324", "student_third" ));  //效率更高

三、删除元素

map<int, int> mp;
for (int i = 0; i < 20; i++){
        mp.insert(make_pair(i, i));
}

mp.erase(0);
mp.erase(mp.begin());

 //等同于mapStudent.clear()
 mp.erase(mp.begin(), mp.end());

四、打印元素

map <int, string> _map; 
_map[200] = "booomm";
_map.insert(pair<int, string>(4, "33333"));
	
//  Map中元素取值主要有at和[]两种操作,at会作下标检查,而[]不会。

//  使用at会进行关键字检查,因为没有100因此该语句会报错	
cout<< _map.at(100).c_str() << endl;         

//  因为已经有4了,不会报错		      
cout << _map.at(4).c_str() << endl;

//  ID_Name中没有关键字200,使用[]取值会导致插入,因此不会报错,但打印结果为空
cout << _map[300].c_str() << endl;

五、寻找元素

map<int, int> mp;
map<int, int>::iterator it_find;
it_find = mp.find(0);

if (it_find != mp.end()){
        it_find->second = 20;
}else{
        printf("no!\n");
}

六、遍历元素

map<int, int>::iterator it;
for (it = mp.begin(); it != mp.end(); it++){
        printf("%d->%d\n", it->first, it->second);
}

七、交换元素

map <int, int> m1, m2;
m1.insert ( pair <int, int>  ( 1, 10 ) );
m1.insert ( pair <int, int>  ( 2, 20 ) );
m2.insert ( pair <int, int>  ( 10, 100 ) );
m2.insert ( pair <int, int>  ( 20, 200 ) );

m1.swap( m2 );

八、获取元素个数

int nSize = mapStudent.size();

九、排序

 Map中的元素是自动按key升序排序,所以不能对map用sort函数

猜你喜欢

转载自blog.csdn.net/qq_30534935/article/details/82921125