map用法

来源:互联网 发布:淘宝贷款买家改卖家 编辑:程序博客网 时间:2024/05/18 07:15
#include   <iostream> #include   <ctime> #include   <map> #include   <string>using   namespace   std;typedef   struct   itemstruct{int   a;char   b[20];}itemS;itemS   s[4] = { { 102, "what" },{ 33, "hello" },{ 198, "world" },{ 45, "c++" }};;int     main(){map<string, itemS>     mymap;int i;string   str[4] = { "1st", "2nd", "3rd", "4th" };for (int i = 0; i<4; i++){mymap.insert(make_pair(str[i], s[i]));//插入数组}map<string, itemS>::iterator   it;for (it = mymap.begin(); it != mymap.end();){if (it->second.a >100){{mymap.erase(it++); }  //----->正确  删除元素//mymap.erase(it);   //  ----->it失效}else        it++;}
/*
for (it = mymap.begin(); it != mymap.end();it++){if (it->second.a >100){{mymap.erase(it);   //  }} 错误的写法
*///first是Key, second是value;for (it = mymap.begin(); it != mymap.end(); it++){cout << it->first;cout << it->second.a << " " << it->second.b << endl;}system("pause");return 0;}/*//解答2:#include<map> #include<iterator> #include<string> #include<iostream> #include<cstring> using namespace std;struct itemstruct{int a;char b[20];itemstruct(int t, char*str){a = t;strcpy_s(b, str);}};int main(){map<string, itemstruct>mymap;mymap.insert(make_pair("a", itemstruct(10, "hanzhou")));mymap.insert(make_pair("ab", itemstruct(20, "fuzhou")));mymap.insert(make_pair("abc", itemstruct(30, "zhengzhou")));mymap.insert(make_pair("abcd", itemstruct(200, "wuhan")));mymap.insert(make_pair("abcde", itemstruct(150, "kunming")));mymap.insert(make_pair("abcdef", itemstruct(50, "xiamen")));map<string, itemstruct>::iterator it = mymap.begin();while (it != mymap.end()){if ((it->second).a>100)mymap.erase(it++);else it++;}it = mymap.begin();while (it != mymap.end()){cout << it->first << " " << (it->second).a << " " << (it->second).b << endl;it++;}system("PAUSE");return 0;}/*解答3:for (map<string, itemstruct>::iterator i = mymap.begin(); i != mymap.end();){if (i->second.a > 100)i = mymap.erase(i);else++i;}*/