【问题标题】:How can I use struct as key? [duplicate]如何使用 struct 作为键? [复制]
【发布时间】:2020-08-28 12:12:03
【问题描述】:

我有以下代码,我遇到了一些错误,例如:

struct duplicatedTurns
    {
        int nodeId;
        int min;
        int max;

        bool operator==(const duplicatedTurns& other) const
        {
            return nodeId == other.nodeId && min == other.min && max == other.max;
        }

I solved it here to following code:
bool operator<(const duplicatedTurns& other) const
{
if (nodeId != other.nodeId) return nodeId < other.nodeId;
if (min != other.min) return min < other.min;
if (max != other.max) return max < other.max;
return false;
}

    };

我要使用的容器:

std::map<duplicatedTurns, int> selected;

在我想在那里插入元素之后:

selected.insert(duplicatedturns{it->nodeId, std::min(it->toLinkId, it->fromLinkId), std::max(it->toLinkId, it->fromLinkId)}, "here: increment the number if the key are the same" );

【问题讨论】:

  • “一些错误”不是很有帮助。你遇到了什么错误?
  • 要将struct用作键,需要有一个比较运算符&lt;
  • 我正要写一个答案。我得到了this。也许这足以让你继续前进。
  • @TedLyngmo。谢谢,这就是我的意思。顺便说一句,我想通了。
  • @MarcellJuhasz 太棒了!快乐黑客! :-) 你推荐使用std::tie 作为operator&lt; 中的逻辑。它使得它很多更容易阅读和维护。在创建符合地图要求的严格弱排序的运算符时也很容易出错。

标签: c++ c++11 struct key stdmap


【解决方案1】:

如何在 std::map 中使用 struct 作为键?

要么通过使用std::map 的默认比较函数std::less 使类小于可比较(这可以通过为满足指定要求的operator&lt; 定义重载来实现),或者通过提供自定义比较函数作为std::map 的模板参数。

【讨论】:

    【解决方案2】:

    在 C++ 中,Map 默认是有序的。这就是为什么必须定义 operator

    【讨论】:

      猜你喜欢
      • 2011-07-18
      • 1970-01-01
      • 2020-07-07
      • 1970-01-01
      • 1970-01-01
      • 2016-06-16
      • 2020-02-28
      • 1970-01-01
      相关资源
      最近更新 更多