c++ - 使用 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==,但没有工作。
解决方案
它们是相同的键,因为您的自定义比较器使用分数作为键。试试这个
bool operator< (const Info &x) const
{
return name < x.name;
}
如果您希望名称作为键,但要按分数对映射进行排序,那么恐怕您不走运,因为映射按定义按键排序。您将不得不选择另一种数据结构或另一种算法。
推荐阅读
- python - 我们如何在 Django 中创建插件和 Play 架构?
- abap - 在同一个alv屏幕中显示多个表
- scala - 将 RDD 数据写入 avro 文件时出错
- html - 从两侧围绕图像/形状包装两列文本html css
- c++ - 如何从特定位置开始读取文件c ++
- drools - 如何使用java应用程序在本地执行drools kjar而不使用kie-server容器?
- ios - URLSession 不返回任何内容
- c - 您可以在指向数组的指针中打印内容吗?
- clockify - 检索 Clockify 工作区时出现错误 500
- ajax - 如何克服 REST API 中的超时?