map容器
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main(){
//初始化map
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"));
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"));
mapStudent[1] = "student_o";
mapStudent[2] = "student_t";
mapStudent[3] = "student_t";
//正序遍历
map<int, string>::iterator iter;
for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
cout << iter->first << ' ' << iter->second << endl;
//逆序遍历
map<int, string>::reverse_iterator iter2;
for(iter2 = mapStudent.rbegin(); iter2 != mapStudent.rend(); iter2++)
cout << iter2->first << " " << iter2->second << endl;
//数组方式访问
for(int nindex = 1; nindex <= mapStudent.size(); nindex++)
cout << mapStudent[nindex] << endl;
cout << mapStudent.size() << endl << endl;
//查找key
iter = mapStudent.find(1);
if(iter != mapStudent.end())
cout << "Find, the value is " << iter->second << endl;
else
cout << "Do not Find" << endl;
//删除元素
iter = mapStudent.find(1);
mapStudent.erase(iter);
int n = mapStudent.erase(2);//如果删除了会返回1,否则返回0
for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
cout << iter->first << ' ' << iter->second << endl;
//清空
mapStudent.clear();
mapStudent.erase( mapStudent.begin(), mapStudent.end() );
return 0;
}