【问题标题】:C++ set<T> What is the most appropriate solution? [duplicate]C++ set<T> 什么是最合适的解决方案? [复制]
【发布时间】:2020-01-22 07:29:15
【问题描述】:

我无法使用 C++ Set 来使用 Class 或 Struct。我在互联网和 stackoverflow 上搜索,但找不到示例。 传统上,由于我的调用,似乎不可能找到除 int 和 string 样本以外的样本。希望有朋友帮忙。

感谢回复的朋友。

using namespace std;

struct DemoData
{
    int             id;
    string          Pairs;
    double          Price;

};

int main()
{
    DemoData myDemoDara  ;
    myDemoDara.id = 1; myDemoDara.Pairs = "GBPJPY"; myDemoDara.Price = 9.34;
    set<DemoData> setVeri  ;    //**It gives errors during compilation.**

    setVeri.insert(listem);

    return 0; 
}

【问题讨论】:

  • 询问构建错误时,始终将编译器的完整错误输出复制粘贴(作为文本!)到问题本身。
  • 至于我的问题是,你的结构没有operator&lt; 函数。 std::setordered(即元素已排序),您需要一个小于比较运算符(operator&lt; 重载)来比较结构的排序。

标签: c++ linked-list set generic-list generic-collections


【解决方案1】:

您必须为您的结构 DemoData 提供自定义 operator &lt;

struct DemoData
{
    int             id;
    string          Pairs;
    double          Price;
    bool operator < (const DemoData& other) const {
     return std::tie(   id, Pairs, Price) < 
            std::tie(   other.id, other.Pairs, other.Price) ;
    }
};

【讨论】:

  • 这部分的工作逻辑是什么? bool operator
  • @UmitTerzi std::set&lt;T&gt; 包含一组已排序的 T 类型的唯一对象。 std::set&lt;T&gt; 将使用std::less&lt;T&gt; 来比较DemoDatastd::less&lt;T&gt; 使用operator&lt;,所以你的类必须提供这个运算符,因为它不能直接推断出你想如何比较@987654332 的这两个对象@ 并插入std::setstd::tie 让生活更轻松,提供严格的弱排序。您可以在std::sethere上搜索详细信息
  • 感谢您提供详细信息。尽管我读了这么多,但我不明白其他网站上写的是什么。
猜你喜欢
  • 1970-01-01
  • 2014-04-13
  • 2023-04-07
  • 1970-01-01
  • 2021-07-11
  • 2020-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多