multimap 使用方法
来源:互联网 发布:美即和一叶子知乎 编辑:程序博客网 时间:2024/06/05 06:52
#include <iostream>#include <string>#include <map>using namespace std;//性别枚举enum Sex{ Man, Woman};//测试结构体struct Student{ string name; int sex; int age;};typedef multimap<string,Student> STU;typedef STU::const_iterator CIT;typedef pair<CIT,CIT> Range;int main(int argc, char* argv[]){ Student s1,s2,s3; s1.name = "a"; s1.sex = Man; s1.age = 18; s2.name = "b"; s2.sex = Woman; s2.age = 20; s3.name = "c"; s3.sex = Man; s3.age = 21; STU stu; stu.insert(make_pair("stu1",s1)); stu.insert(make_pair("stu2",s2)); stu.insert(make_pair("stu1",s3)); //查找方法一 cout << "查找方法一"<<endl; Range range=stu.equal_range("stu1"); for(CIT cit1 = range.first;cit1!=range.second;cit1++) { cout << cit1->first <<',' << cit1->second.name << ',' << cit1->second.sex << ',' << cit1->second.age << ',' << endl; } //查找方法二 cout << "查找方法二"<<endl; CIT cit2; for (cit2 = stu.lower_bound("stu1");cit2 != stu.upper_bound("stu1"); ++cit2) { cout << cit2->first <<',' << cit2->second.name << ',' << cit2->second.sex << ',' << cit2->second.age << ',' << endl; } //查找方法三 cout << "查找方法三" << endl; CIT cit; for( cit = stu.begin(); cit != stu.end(); cit++ ) { if( cit->first == "stu1" ) { cout << cit->first <<',' << cit->second.name << ',' << cit->second.sex << ',' << cit->second.age << ',' << endl; } } //遍历 cout << "遍历" << endl; CIT cit3 = stu.begin(); while(cit3 != stu.end()) { cout << cit3->first << ',' << cit3->second.name << ',' << cit3->second.sex << ',' << cit3->second.age << ',' << endl; cit3++; } string search_item("stu2"); //擦出元素,返回其下标 STU::size_type cnt=stu.erase(search_item); cout << cnt; //删除后 遍历 cout << "遍历" << endl; cit3 = stu.begin(); while(cit3 != stu.end()) { cout << cit3->first << ',' << cit3->second.name << ',' << cit3->second.sex << ',' << cit3->second.age << ',' << endl; cit3++; } cin.get(); return 0;}