在最近一直在阅读xx项目,看到里面用到了map,读大学期间基本上从来没用到过这种stl(大学就用了Vector和list)。下面对map敲如下代码:
运行截图如下:
代码如下:
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main(){
map<int, string> mapStudent;
mapStudent.insert(pair<int, string>(1, "student_one"));
mapStudent.insert(pair<int, string>(2, "student_two"));
mapStudent.insert(pair<int, string>(3, "student_three"));
map<int, string>::iterator iter;
for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++){
cout << iter->first << " " << iter->second << endl;
}
cout << endl;
//mapStudent.clear();
mapStudent.insert(map<int, string>::value_type(4, "student_four"));
mapStudent.insert(map<int, string>::value_type(5, "student_five"));
mapStudent.insert(map<int, string>::value_type(6, "student_six"));
for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
cout << iter->first << " " << iter->second << endl;
cout << endl;
//mapStudent.clear();
mapStudent[7] = "student_seven";
mapStudent[8] = "student_eight";
mapStudent[9] = "student_nine";
for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
cout << iter->first << " " << iter->second << endl;
cout << endl;
pair<map<int, string>::iterator, bool>insert_pair;
insert_pair = mapStudent.insert(map<int, string>::value_type(1, "student_one"));
if (insert_pair.second == true)
cout << "插入<1,student_one>成功!\n";
else
cout << "插入<1,student_one>失败!\n";
insert_pair = mapStudent.insert(map<int, string>::value_type(10, "student_ten"));
if (insert_pair.second == true){
cout << "插入<10,student_ten>成功!\n开始遍历!\n";
for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
cout << iter->first << " " << iter->second << "\n";
cout << endl;
}
else
cout << "插入<10,student_ten>失败!\n";
//打印大小
cout << "mapStudent的大小为:" << mapStudent.size() << endl << endl;
//用数组方式遍历
for (int i = 1; i <= mapStudent.size(); i++) //此处从1开始,非0开始
cout << mapStudent[i] << endl;
cout << endl;
//查找
map<int, string>::iterator iter_find;
iter_find = mapStudent.find(5);
if (iter_find != mapStudent.end())
cout << "Find, the value is " << iter_find->second << endl;
cout << endl;
//删除和清空和Vector类似
getchar();
return 0;
}