Mar*_*oof 1 c++ dictionary stl comparator
#include<bits/stdc++.h>
using namespace std;
struct segment{
int a;
int b;
int c;
bool const operator<(const segment &o) const {
return a < o.a;
}
};
int main()
{
map<segment,int> myMap;
map<segment,int>::iterator it;
struct segment x,y,z;
x.a=2;
x.b=4;
x.c=6;
y.a=2;
y.b=5;
y.c=8;
z.a=2;
z.b=4;
z.c=6;
myMap[y]++;
myMap[z]++;
myMap[x]++;
for( it =myMap.begin(); it != myMap.end(); it++)
cout<<(*it).first.a<<" "<<(*it).second<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它给出了结果
2 3
Run Code Online (Sandbox Code Playgroud)
但我希望它打印
2 1
2 2
Run Code Online (Sandbox Code Playgroud)
简而言之,如果输入完全相同的结构实例而不是制作新副本,我想增加地图的值
IMO比较多个成员的最佳方法是使用,std::tie因为它更难搞乱:
bool const operator<(const segment &o) const {
return std::tie(a, b, c) < std::tie(o.a, o.b, o.c);
}
Run Code Online (Sandbox Code Playgroud)
编辑:只想将此链接添加到cppreference作为示例几乎就是您的问题.