如何通过编译由结构构成的std :: pair来修复错误?

时间:2019-07-17 22:34:31

标签: c++ c++11 multimap std-pair

我正在建立一个新项目,其中包括一个理想地由已定义结构构成的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)

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

1 个答案:

答案 0 :(得分:1)

要放置在myStruct中的std::multimap需要strict-weak-ordering,因此需要定义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&)不需要存在(这就是它们在上面的示例程序中不存在的原因)。