【问题标题】:overloading operators for struct as map key重载结构运算符作为映射键
【发布时间】:2023-03-30 08:25:01
【问题描述】:

您好,我在重载结构的运算符以用作键时遇到问题。这是我打算用作映射键的结构,基本上它有 2 个字符数组:

struct FConfig
{
    char product[3];
    char exchange[4];
    bool operator < (const FConfig &rhs) const
    {
        return (strcmp(product, rhs.product) < 0 || 
                 strcmp(exchange, rhs.exchange <0));
    }
};

我的比较是,只要产品或交换之一不等于 rhs,那么密钥就被认为是唯一的。我使用它,在运行时我得到“无效的运算符

【问题讨论】:

  • 如果你为你的类提供一个 std 例程时必须表现得像一个操作符。我猜,您的运算符不是传递性的 - 您可能会发现 FConfig 的三个值,例如 A

标签: c++


【解决方案1】:

您对operator &lt; 应该如何工作的困惑很常见。你希望它看起来像这样:

bool operator < (const FConfig &rhs) const
{
   int product_comparision = strcmp(product,rhs.product);
   if (product_comparision<0) return true;
   if (product_comparision>0) return false;
   return strcmp(exchange,rhs.exchange)<0;
}

由于product 是您的主键,您唯一考虑辅助键的情况是主键值是否相等。

【讨论】:

  • 如果这些是正确的字符串,您可以使用return std::make_pair(product, exchange) &lt; std::make_pair(rhs.product, rhs.exchange);(或std::tie)。
  • 是的,这让我很困惑,因为在设计键时,我只是想它们是否相等,而不是“小于”。您的解决方案和解释解决了我的问题。非常感谢沃恩 :)
猜你喜欢
  • 2020-11-08
  • 2015-09-27
  • 1970-01-01
  • 2013-04-28
  • 2010-09-13
  • 2012-11-19
  • 1970-01-01
  • 2019-01-18
  • 1970-01-01
相关资源
最近更新 更多