1.示例一:map<int, int> mp;用法
#include <iostream>
#include <map>
using namespace std;
int main(){
map<int, int> mp;
for (int i = 0; i < 20; i++){
mp.insert(make_pair(i, i));
}
map<int, int>::iterator it_find;
it_find = mp.find(1);//查找key为的1键值
cout << it_find->first <<" -> " << it_find->second << endl << endl;
map<int, int>::iterator it;
for (it = mp.begin(); it != mp.end(); it++){
cout << it->first << " -> " << it->second << endl;
}
return 0;
}
2.示例二:map<string, unique_ptr<int>> myMap;用法
#include <iostream>
#include <map>
#include <memory>
using namespace std;
int main() {
map<string, unique_ptr<int>> myMap;
//1.向map中插入值int类型
myMap["key1"] = make_unique<int>(10);
myMap["key2"] = make_unique<int>(20);
myMap["key3"] = make_unique<int>(30);
//2.修改"key2"的值.
cout << "key2 = " << *myMap["key2"] << endl;
*myMap["key2"] = 50;
cout << "修改:key2 = " << *myMap["key2"] << endl;
//3.访问map中存储的值.
for(const auto& pair : myMap) {
cout << pair.first << " = " << *pair.second << endl;
}
//2.向map中插入值string类型
map<string, unique_ptr<string>> stu;
stu["name"] = make_unique<string>("Mr Li");
stu["school"] = make_unique<string>("HFOO");
printf("\nxxx------line = %d, name = %s\n",__LINE__,(*stu["name"]).c_str());
*stu["name"] = string("Mr Wang");
printf("xxx------line = %d, name = %s\n\n",__LINE__,(*stu["name"]).c_str());
for(const auto &pair : stu)
printf("xxx------line = %d, %s = %s\n",__LINE__,(pair.first).c_str(),(*pair.second).c_str());
return 0;
}