【问题标题】:problem with using struct as std::map key使用 struct 作为 std::map 键的问题
【发布时间】:2020-07-07 02:47:25
【问题描述】:

我的代码是这样的:

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 相同)

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

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

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

【问题讨论】:

    标签: c++ data-structures stl std


    【解决方案1】:

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

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

    如果您希望名称为键,但地图按分数排序,那么恐怕您不走运,因为地图按定义按键排序。您必须选择另一种数据结构或另一种算法。

    【讨论】:

    • 我想同时使用名称和分数作为键,我想我已经通过使用“ if (score == x.score) return name
    • 不,这是一个无效的比较函数,因为它没有强加严格的弱排序。试试这个版本return score &lt; x.score || (score == x.score &amp;&amp; name &lt; x.name); }
    • 那么 std::map 内部的机制是什么? std::map 如何决定它们是否相同?我只提供了 operator
    • @BunsenBurner 没错,不,更正,如果两者都是 false 它们是同一个键。
    • PS boost.org/sgi/stl/StrictWeakOrdering.html,你必须有严格的弱排序,否则你的代码会崩溃(最终)。
    猜你喜欢
    • 2011-07-18
    • 1970-01-01
    • 2014-08-06
    • 2011-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    相关资源
    最近更新 更多