【问题标题】:Appending map that uses Struct as a "multikey" and std::vector as mapped value附加使用 Struct 作为“多键”和 std::vector 作为映射值的映射
【发布时间】:2020-06-05 16:30:36
【问题描述】:

在下面的代码中,它仅在第一次调用appendMyList() 时附加myList,并且大小保持为1,所以有人可以在这里解释什么问题:

struct MyKey {
  int accValue;
  std::string name;
};

inline bool operator<(MyKey a, MyKey b){
  return a.accValue < b.accValue && a.name < b.name;
}

inline bool operator==(MyKey a, MyKey b){
  return a.accValue == b.accValue && a.name == b.name;
}

typedef std::map<MyKey, std::vector<int>> MyList;

class MyClass {
    public:
    void appendMyList(int accVal, std::string name, int element) {
        myList[MyKey{accVal, name}].push_back(element);
        cout<<endl<<"Size after"<< myList.size()<<endl;
    }

   MyList myList;
};

我看到了类似的帖子here,但我的运营商没有发现任何问题,所以我猜是别的什么?

这就是我调用函数的方式:

int main()
{
    MyClass imHere;
    int a = 1;
    std::string yaya = "name";
    for (int i = 0; i<10; i++) {
            imHere.appendMyList((++a), yaya, i);
    }

    return 0;
};

【问题讨论】:

  • return (a.accValue &lt; b.accValue) || (a.accValue == b.accValue &amp;&amp; a.name &lt; b.name);
  • @cigien 我编辑了 PiotrSkotnicki 嗯,不知道你想说什么?
  • 这就是你的operator&lt; 的样子。或者,return std::tie(a.accValue, a.name) &lt; std::tie(b.accValue, b.name);
  • names 相同时,即使accValues 不同,您的operator&lt; 也会返回false。所以你的地图永远不会插入任何其他东西。
  • 感谢帮助,== 运算符可以保持不变吗?

标签: c++ vector key stdmap multikey


【解决方案1】:

std::map 不允许存储重复项。但是,它不使用operator== 来检查元素的相等性。它使用operator&lt; 来对元素进行排序以及检查等价性

也就是说,如果!(a &lt; b) &amp;&amp; !(b &lt; a)std::map 认为ab 等效,因此使用operator&lt; 插入的元素不会超过一个,因为name 在所有元素中都是相同的,因此(a &lt; b)(b &lt; a) 都返回 false

相反,您应该使用:

inline bool operator<(MyKey a, MyKey b) {
  return a.accValue < b.accValue || (a.accValue == b.accValue && a.name < b.name);
}

或:

inline bool operator<(MyKey a, MyKey b) {
  return std::tie(a.accValue, a.name) < std::tie(b.accValue, b.name);
}

【讨论】:

    猜你喜欢
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 2018-10-02
    • 2012-01-23
    • 2015-10-20
    • 2018-02-02
    • 1970-01-01
    相关资源
    最近更新 更多