结构体作为map的Key (百度很多答案都有坑)

百度搜了几个版本的代码,发现好几个人写的代码都有坑,比如这个
https://blog.csdn.net/stpeace/article/details/46553525?_t=t
和这个https://www.cnblogs.com/fuqia/p/9511994.html

#include 
#include 
#include 
using namespace std;

struct Info
{
    string name;
    int score;

    bool operator< (const Info &x) const
    {
        return score < x.score;
    }
};

int main()
{
    Info a, b;

    a.name = "eric";
    a.score = 90;

    b.name = "cat";
    b.score = 85;


    map m;
    m[a] = 1;
    m[b] = 2;

    map::iterator it;
    for(it = m.begin(); it != m.end(); it++)
    {
        cout << it->first.name << endl;
    }

    return 0;
}

坑:假如a.score 和 b.score都一样, 那么map会判断 a 和 b是同一个key,尽管a.name和b.name不一样。
map的内部机制是, 根据你提供的<操作符, 判断 a < b 和 b < a是否同时成立, 假如同时成立,那么判定a和b是同一个key, 所以<操作符,不能只考虑score这个成员变量,还要把name拉进来

详细术语,见:https://www.boost.org/sgi/stl/StrictWeakOrdering.html

改法:
return score < x.score || (score == x.score && name < x.name);

你可能感兴趣的:(结构体作为map的Key (百度很多答案都有坑))