【问题标题】:Comparison Operator for Structure key in C++ MapC++ Map 中结构键的比较运算符
【发布时间】:2015-06-14 18:53:59
【问题描述】:
#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;
}

结果为

2 3

但我希望它打印出来

2 1
2 2

简而言之,如果提供完全相同的结构实例而不是制作新副本,我想增加映射的值

【问题讨论】:

  • 那你得换个less操作符,比较所有成员。
  • 我没听懂你说的。你能给出比较器的代码吗?
  • 我尝试了一个嵌套的 if else 语句,但它没有正常工作
  • 您不应该包含bits/stdc++.h,这是一个实现标头。包括mapiostream

标签: c++ dictionary stl comparator


【解决方案1】:

IMO 比较多个成员的最佳方法是使用 std::tie,因为它更难搞砸:

bool const operator<(const segment &o) const {
    return std::tie(a, b, c) < std::tie(o.a, o.b, o.c);
}

编辑:只想将此链接添加到cppreference 作为示例,几乎就是您的问题。

【讨论】:

    【解决方案2】:

    您可以将您的 less 运算符更改为:

    bool const operator<(const segment &o) const {
        return a < o.a || (a == o.a && b < o.b) || (a==o.a && b==o.b && c < o.c) ;
    }
    

    这将按 a、b、c 的顺序比较值。

    但是你可以随意改变它来比较结构。

    【讨论】:

      【解决方案3】:

      就您的map 而言,这里只有一个独特的对象。根据您指定的比较以及隐含的等价,x == yy == z。为什么?它们都不比另一个小,所以根据STL逻辑比较,它们一定是等价的。

      也许您正在寻找std::multimap

      或者,如果您想根据所有成员定义不等式(因此隐含等价),您可以执行以下操作:

      #include <tuple>
      
      bool const operator<(const segment &o) const {
          return std::make_tuple(a, b, c) < std::make_tuple(o.a, o.b, o.c);
      }
      

      附:您应该避免包含来自bits 的内容,因为您正在包含来自实现的内容。相反,请尝试使用诸如

      之类的东西
      // See? no bits.
      #include <map> 
      

      【讨论】:

      • 如果再次输入相同的键,我想增加映射的值。为了使键相等,我想要 a==o.a,b==o.b,c==o.c。我可以在地图上实现吗?
      猜你喜欢
      • 2013-04-28
      • 1970-01-01
      • 2011-08-10
      • 1970-01-01
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 2012-01-12
      相关资源
      最近更新 更多