我正在尝试为每个给定的时间间隔打印输入数据中出现的次数,例如对于输入:
4
1 5
6 8
6 8
4 7
该程序应打印:
1 5:1
6 8:2
4 7:1
这是我的代码
struct Interval
{
long unsigned int start, end;
};
bool operator<(const Interval& i1, const Interval& i2)
{
bool renvoie = true;;
if(i1.start < i2.start)
{
renvoie = true;
}
else if(i1.start== i2.start && i1.end>=i2.end)
renvoie = true;
else
renvoie = false;
return renvoie;
}
bool operator==(const Interval& i1, const Interval& i2)
{
return (i1.start==i2.start && i1.end==i2.end);
}
int main()
{
int nbr;
cin>>nbr;
map<Interval, int> occurence;
for(int i=0;i<nbr;i++)
{
Interval jetable;
cin>>jetable.start;
cin>>jetable.end;
occurence[jetable]++;
}
for(map<Interval,int>::iterator it = occurence.begin(); it!=occurence.end(); ++it)
{
cout << (it->first).start <<" " <<(it->first).end<<" "<<(it->second)<<endl;
}
}
问题是,两个相同的间隔被认为是不同的,为什么?
最佳答案
因为这就是您的比较者所说的。如果将相同的对象作为两个参数传递,则重载将返回true
。您的<
重载,在这种情况下返回true
。这意味着您的<
重载表明第一个值小于第二个值,根据定义,当它们相等时是不可能的。
只需将其更改为在这种情况下返回false(将>=
更改为>
即可满足要求)。
关于c++ - 如何在 map 中使用结构作为关键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60588616/