map自定义键

这个问题的起源是,当时比赛的时候我想用map来标记结构体变量是否出现过,当时一直调不出来。现在才知道,重载<运算符(之所以只重载<运算符是因为stl的map实现只用到了<运算符)这里写错了,当a.x==b.x ,a.y==b.y, a.z==b.z的时候也是有返回值的,而且要返回false。

#include<bits/stdc++.h>
using namespace std;
#define fuck(x) cout<<#x<<"     "<<x<<endl;
struct node
{
    int x,y,z;
    node(int x=0,int y=0,int z=0)
    {
        this->x=x;
        this->y=y;
        this->z=z;
    }
    friend bool operator <(const node&a,const node&b)
    {
        if(a.x!=b.x)
            return a.x<b.x;
        else
            if(a.y!=b.y)
                return a.y<b.y;
            else
                if(a.z!=b.z)
                    return a.z<b.z;
                else
                    return false;
    }
//    friend bool operator ==(const node&a,const node&b)
//    {
//        return a.x==b.x&&a.y==b.y&&a.z==b.z;
//    }

};
map<node,int>mp;
pair<node,int> p;
int main()
{
    fuck(mp.size());
    node key=node(1,1,1);
    //cout<<key.x<<"  "<<key.y<<"   "<<key.z<<endl<<endl;
    if(mp[key])
        cout<<"HAVE"<<endl;
    else
        cout<<"NO HVAE"<<endl;
    for(auto it:mp)
        cout << it.first.x << "     " << it.first.y<<"     "<<it.first.z<<"     "<<it.second << endl;
    fuck(mp.size());
    mp[key]=1;
    for(auto it:mp)
        cout << it.first.x << "     " << it.first.y<<"     "<<it.first.z<<"     "<<it.second << endl;
    fuck(mp.size());
    if(mp[key])
        cout<<"HAVE"<<endl;
    else
        cout<<"NO HVAE"<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/eason9906/p/11754763.html