如何修复编译由结构组成的 std::p air 时出现的错误

How to fix error with compiling a std::pair made of structs?

本文关键字:air 错误 何修复 std 结构 编译      更新时间:2023-10-16

我正在建立一个新项目,其中包括一个理想情况下由定义的结构组成的std::multimap

我已经尝试了make_pair()multimap.insert(),到目前为止还没有奏效。

我的代码基本上是:

struct myStruct {
  myStruct() {}
  myStruct(const myStruct &other) : foo(other.foo), bar(other.bar) {}
  Neighbor &operator=(const myStruct &other) {
    if (this != &other) {
      foo = other.foo;
      bar = other.bar;
    }
    return *this;
  }
  string foo;
  std::vector<int> bar;
};
std::multimap<myStruct, myStruct> myMultiMap;
myStruct myStruct1;
myStruct myStruct2;
m_neighborMap.insert(std::pair<myStruct, myStruct>{myStruct1, myStruct2});

但是,当我编译代码时,我收到以下错误:

/Library/Developer/CommandLineTools/usr/include/c++/v1/__functional_base:55:21: error: invalid operands to binary expression ('const myStruct' and 'const myStruct')
candidate template ignored: could not match 'pair<type-parameter-0-0, type-parameter-0-1>' against 'const myStruct'
operator< (const pair<_T1,_T2>& __x, const pair<_T1,_T2>& __y)

有谁知道如何正确初始化这对结构?谢谢!

要放置在std::multimap中的myStruct需要严格-弱-排序,因此需要定义operator <

最简单的方法是使用 std::tie 来设置它:

#include <vector>
#include <map>
#include <algorithm>
#include <string>
#include <iostream>
struct myStruct 
{
    std::string foo;
    std::vector<int> bar;

    // define an operator <
    bool operator <(const myStruct& m) const 
    {
        return std::tie(foo, bar) < std::tie(m.foo, m.bar);
    }
};
int main()
{
    //test
    myStruct m1;
    myStruct m2;
    m1.foo = "abc";
    m1.bar = std::vector<int> {1,2,3,4};
    m2.foo = "123";
    m2.bar = std::vector<int> {4,5,6,7,8};
    std::multimap<myStruct, myStruct> myMultiMap;
    //insert into map 
    myMultiMap.insert({m1, m2});
    myMultiMap.insert({m2, m1});
    // output number of entries
    std::cout << myMultiMap.size();
}

输出:

2

此外,由于std::stringstd::vector已经是可复制的,因此myStruct不需要定义赋值运算符和复制构造函数。 因此operator =myStruct(constmyStruct&)不需要存在(这就是为什么它们在上面的示例程序中不存在的原因(。