stl map 使用结构体作为键

#include <iostream>
#include <map>
#include <string>
using namespace std;

struct package
{
    int id;
    string data;
    bool operator<(const package& tmp) const{
        if(this->id < tmp.id)
            return true;  //自定义排序规则
        return false;
    }
};

int main() {
    map<package,int> tmp;
    package a = {3,"a"};
    package b = {2,"b"};
    tmp.insert(make_pair(a, 0));
    tmp.insert(make_pair(b, 0));  //插入
    map<package, int>::iterator i;
    for(i = tmp.begin(); i != tmp.end(); i++)
        cout << i->first.id << " " << i->first.data << " " << i->second << endl;
}

猜你喜欢

转载自blog.csdn.net/chent86/article/details/78986672
今日推荐