C++第10课 STL容器 (九)
1.map(映射)
/* map:映射,一种对应关系 自带排序(按照键去排序) 键唯一,相同键采用最后一次插入的数据,覆盖的方式去处理 存储的数据是: 数对类型(pair) */ void testMap() { map<int, string>str; //1.pair对象插入 str.insert(pair<int, string>(1, "小可爱")); //2.数组法插入 str[-1] = "小甜心"; //3.间接通过make_pair构建一个pair类型 str.insert(make_pair<int, string>(2, "小宝贝")); str[-1] = "小美女"; for (auto v : str) { cout << v.first << "\t" << v.second << "\t"; } cout << endl; map<int,string>::iterator iter=str.begin(); while (iter != str.end()) { cout << (*iter).first << "\t" << (*iter).second << "\t"; iter++; } cout << endl; } class MM { public: MM() = default; MM(string name, int age) :name(name), age(age) {} string getName() { return name; } int getAge() { return age; } bool operator<(const MM& object) const { return this->age < object.age; } friend ostream& operator<<(ostream& out, const MM& mm) { out << mm.name << "\t" << mm.age; return out; } protected: string name; int age; }; class GG { public: GG() = default; GG(string name, int age) :name(name), age(age) {} string getName() { return name; } int getAge() { return age; } friend ostream& operator<<(ostream& out, const GG& gg) { out << gg.name << "\t" << gg.age; return out; } protected: string name; int age; }; template <class _Ty1, class _Ty2> void print(map<_Ty1, _Ty2>& temp) { for (auto v : temp) { //int MM cout << v.first << "\t" << v.second << endl; } } void testUserData() { //可以任意对应 map<int, MM> mmData; mmData[1] = MM("小美人", 18); mmData[3] = MM("小可爱", 29); mmData[2] = MM("小甜心", 28); print(mmData); map<MM, GG> mmgg; //less<int> < mmgg[MM("张三", 18)] = GG("李四", 20); mmgg[MM("王五", 29)] = GG("赵六", 34); mmgg[MM("美女", 45)] = GG("帅哥", 55); cout << mmgg[MM("美女", 45)].getName() << mmgg[MM("美女", 45)].getAge() << endl; print(mmgg); //< map<string, string, less<string>> strData; //和默认是一样,从小到大 //> map<string, string, greater<string>> greaterData; //从大到小 } void testmultimap() { multimap<int, string> mulData; //注意点: 多重映射不能采用下标法赋值 mulData.insert(make_pair<int, string>(3, "测试结果")); mulData.insert(pair<int, string>(1, "多重映射")); mulData.insert(make_pair<int, string>(1, "多重映射2")); for (auto v : mulData) { cout << v.first << "\t" << v.second << endl; } } void testNestMap() { map<int, map<string, MM>> mapData; map <string, MM> mmData; mmData["美女"] = MM("小美", 18); mapData[0] = mmData; cout << mapData[0]["美女"].getName() << mapData[0]["美女"].getAge() << endl; }