【发布时间】: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