首页 > 解决方案 > 使用 struct 作为 std::map 键的问题

问题描述

我的代码是这样的:

struct Info
{
    string name;
    int score;
    bool operator< (const Info &x) const
    {
        return score < x.score;
    }
};
int main(int argc, char *argv[])
{
    Info a, b;
    a.name = "eric";
    a.score = 90;
    b.name = "cat";
    b.score = 85;

    map<Info, int> m;
    m[a] = 1;
    m[b] = 2;

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

    return 0;
}

正如预期的那样,它会打印出“cat”和“eric”。但是无论如何,当我将其修改为(使 a.score 和 b.score 相同)</p>

Info a, b;
a.name = "eric";
a.score = 90;
b.name = "cat";
b.score = 90;

它只打印出“eric”,整个地图中只有一个元素。

问题:std::map 是否认为它们是相同的键?我如何让 std::map 认为它们不是同一个键?我尝试了 operator==,但没有工作。

标签: c++data-structuresstlstd

解决方案


它们是相同的键,因为您的自定义比较器使用分数作为键。试试这个

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

如果您希望名称作为键,但要按分数对映射进行排序,那么恐怕您不走运,因为映射按定义按键排序。您将不得不选择另一种数据结构或另一种算法。


推荐阅读