1.创建
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main() {
/*using std::map;
using std::string;
using std::cout;*/
map<string, string> myMap1 = {
{"Name", "ClearLove"},
{"Gender", "Male"},
{"Position", "Jungle"},
{"ID", "1"}
};
map<string, string> myMap2;
myMap2["Name"] = "TheShy";
myMap2["Gender"] = "Male";
myMap2["Position"] = "Top";
myMap2["ID"] = "2";
map<string, string> myMap3(myMap2.begin(), myMap2.end());
myMap3["ID"] = "3";
map<string, string> myMap4(myMap3);
myMap4["ID"] = "4";
map<string, string> mapArr[4] = { myMap1, myMap2, myMap3, myMap4 };
map<string, string>::iterator iter;//这种方法能够取出保存在map容器里面的数据
for (int iMap = 0; iMap < 4; iMap++) {
cout << "Map " << iMap + 1 << " of 4\n";
for (iter = mapArr[iMap].begin(); iter != mapArr[iMap].end(); iter++) {
cout << "key: " << iter->first << " , value: " << iter->second << ".\n";
}
}
return 0;
}
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main() {
map<int, int> dict1;
dict1[0] = 1;
dict1[1] = 2;
dict1[10] = 10;
map<int, int>::iterator iter;
iter = dict1.begin();
while (iter != dict1.end()) {
cout << iter->first << " : " << iter->second << endl;
iter++;
}
//取出值的方法
int a = dict1[0];
cout << a << endl;
cout << "usually:" << dict1.at(0) << endl;
map< int,int >::iterator myIter = dict1.find(0);
cout << myIter->first << "key<-::->value" << myIter->second << endl;
}
2.修改和增加
#include <map>
#include <string>
#include <iostream>
int main()
{
map<int , string>dict1;
for(int i = 0;i<=4;i++)
{
dict1[i]="hello world";
cout<<dict1[i]<<endl;
}
cout<<"++++++++++++++++++++"<<endl;
//修改
string a;
a = "12345678";
dict1[0] =a;
for(int i = 0;i<=4;i++)
{
cout<<dict1[i]<<endl;
}
dict1[5]="12366";
cout<<dict1[5]<<endl;
//增加
cout<<"++++++++insert++++++++++++"<<endl;
dict1.insert(pair<int,string>(9,"insert")) ;
cout<<dict1[9]<<endl;
//删除
cout<<"+++++++++erase+++++++++++"<<endl;
dict1.erase(2);
for(int i = 0;i<=9;i++)
{
cout<<dict1[i]<<endl;
}
}