[C++] 自定义复杂类型作为map的键和值的情况

#include <iostream>
#include <vector>
#include <map>

using namespace std;

// 定义类型Stu,重载运算符 <
class Stu {
public:
    string name;
    int age;

public:
    Stu(string _name, int _age){
        name = _name;
        age = _age;
    }
    ~Stu(){};
    bool operator <(const Stu& s) const;
};

bool Stu::operator <(const Stu &s)  const
{
    if(this->age<s.age)
        return true;
    else
        return false;
}

// 定义类型Key,重载运算符 <
class Key{
public:
    int _key;

public:
    Key(){};
    Key(int v){
        _key=v;
    };
    ~Key(){};
    bool operator <(const Key& key) const;
};

bool Key::operator <(const Key &key)  const
{
    if(this->_key<key._key)
        return true;
    else
        return false;
}

int main() {
    Stu s1("Tina", 18);
    Stu s2("Linda", 10);
    Stu s3("Tom", 15);
    Key one(1);
    Key two(2);
    Key three(3);
    vector<Key> keys;
    keys.push_back(one);
    keys.push_back(two);
    keys.push_back(three);
    // 键为Stu,值为vector<Key>
    map<Stu,vector<Key>> ClassMap;
    ClassMap.insert(make_pair(s1,keys));
    ClassMap.insert(make_pair(s2,keys));
    ClassMap.insert(make_pair(s3,keys));
    // 输出检查结果
    map<Stu,vector<Key>>::iterator itor=ClassMap.begin();
    while(itor!=ClassMap.end())
    {
        cout<<itor->first.name<<" ~~ "<<endl;
        for (auto item: itor->second){
            cout << item._key << "  ";
        }
        cout << endl;
        ++itor;
    }
    cout << "===============" << endl;
    // 复制这样复杂类型的map也是妥妥的
    map<Stu, vector<Key>> new_map = ClassMap;
    ClassMap.erase(ClassMap.begin(), ClassMap.end());
    map<Stu,vector<Key>>::iterator iter=new_map.begin();
    while(iter!=new_map.end())
    {
        cout<<iter->first.name<<" ~~ "<<endl;
        for (auto item: iter->second){
            cout << item._key << "  ";
        }
        cout << endl;
        ++iter;
    }
}

结果是:

Linda ~~ 
1  2  3  
Tom ~~ 
1  2  3  
Tina ~~ 
1  2  3  
===============
Linda ~~ 
1  2  3  
Tom ~~ 
1  2  3  
Tina ~~ 
1  2  3  

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/qq_32732581/article/details/87892306