map用法:
#include<cstdio> #include<cstring> #include<string> #include<iostream> #include<map> using namespace std; int main() { map<int, string> mapstudent; mapstudent.clear();//清空map 方法1 mapstudent.erase(mapstudent.begin(),mapstudent.end());//清空map 方法2 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(pair<int, string>(5, "student_five")); map<int, string>::iterator iter; //int nsize = mapstudent.size(); //for(int i = 0; i <= nsize; i++)//遍历方法1 // cout<<mapstudent[i]<<endl; for(map<int,string>::reverse_iterator i = mapstudent.rbegin(); i != mapstudent.rend(); i++)//遍历方法2,反方向遍历 cout<<i->first<<" "<<i->second<<endl; //遍历方法3,不写了 iter = mapstudent.find(2);//查找元素 方法1 if(iter != mapstudent.end()) { cout<<"find the num is "<<iter->second<<endl; } else cout<<"error"<<endl; iter = mapstudent.find(3);//删除元素 方法1 mapstudent.erase(iter); // int n = mapstudent.erase(3);//删除元素,方法2 如果删除了会会返回1,没有则返回0 //查找元素 方法2 // Upper_bound函数用法,这个函数用来返回要查找关键字的上界(是一个迭代器) // 例如:map中已经插入了1,2,3,4的话,如果lower_bound(2)的话,返回的2, // 而upper-bound(2)的话,返回的就是3 // Equal_range函数返回一个pair,pair里面第一个变量是Lower_bound返回的迭代器, // pair里面第二个迭代器是Upper_bound返回的迭代器,如果这两个迭代器相等的话, // 则说明map中不出现这个关键字 iter = mapstudent.lower_bound(2); cout << iter->second<<endl; iter = mapstudent.lower_bound(3); cout << iter->second<<endl; iter = mapstudent.upper_bound(2); cout << iter->second<<endl; iter = mapstudent.upper_bound(3); cout << iter->second; pair<map<int,string>::iterator, map<int, string>::iterator>mappair; mappair = mapstudent.equal_range(2); if(mappair.first == mappair.second) cout << "Not find the num"<<endl; else cout << "find"<<endl; mappair = mapstudent.equal_range(3); if(mappair.first == mappair.second) cout << "Not find the num"<<endl; else cout << "find" << endl; return 0; }