c++ - 使用包含键和结构的映射执行 set_intersection 时出错

标签 c++ data-structures struct stdmap

我想找到两张 map 之间的交点。我的 map 有结构 map<int,line> , 其中line是一个结构。问题是当我使用 set_intersection为了执行交集,我得到了图像中表示的以下错误。

image shows the errors i got

下面是我的代码

#include <string>
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
typedef pair<int, int> point;
struct line
{
    int lineid;
    point starting, ending;
};
int main(int argc, char* argv[])
{
    typedef map<int, line> mymap;   
    line w,x,y,z;
    w.lineid = 1;
    w.starting = { 5, 1 };
    w.ending = { 5, 100 };
    x.lineid = 2;
    x.starting = { 20, 56 };
    x.ending = { 120, 56 };
    y.lineid = 3;
    y.starting = { 100, 150 };
    y.ending = { 100, 200 };
    z.lineid = 4;
    z.starting = { 330, 50 };
    z.ending = { 330, 150 };

    mymap bin1;
    bin1.insert({ w.lineid, w });
    bin1.insert({ x.lineid, x });
    bin1.insert({ y.lineid, y });

    mymap bin2;
    bin2.insert({ x.lineid, x });
    bin2.insert({ y.lineid, y });
    bin2.insert({ z.lineid, z });

    mymap out;
    mymap::iterator out_itr(out.begin());
    set_intersection(bin1.begin(), bin1.end(), bin2.begin(), bin2.end(),
                                                 inserter(out, out_itr)); 
    cout << "" << out.size();               

        return 0;
    }

解决此问题的任何帮助都会有所帮助。

最佳答案

编译器提示找不到 operator<比较线对象(你需要比较 std::pair<int, line> ,它的比较器需要比较线)。

你必须为你的行提供一个比较器:

示例:

  bool operator<(const line& other) const
  {
      return other.lineid < lineid; // Or whatever logic you want to compare your lines.
  }

实例 here

注意:

或者,您可以直接向 set_intersection 提供比较器,例如这里有一个 lambda :

 set_intersection(bin1.begin(), 
                  bin1.end(), 
                  bin2.begin(), 
                  bin2.end(),
                  inserter(out, out_itr),
                  [] (const std::pair<int, line>& p1, const std::pair<int, line>& p2) { return p1.first != p2.first; } ); 

关于c++ - 使用包含键和结构的映射执行 set_intersection 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24450381/

相关文章:

struct - 如何访问 svg::node::Value 元组结构的单个字符串字段?

java - List<Double> 使用双 [] 的 RAM?

algorithm - 图时间复杂度

c++ - 这个 "if e is a pack, then get a template name, otherwise get a variable name"是否有效?

c++ - 模板外的类型名

c# - 我应该使用什么数据类型进行版本控制?

ios - 更新已保存的 Codable 结构以添加新属性

c++ - 在 C++ 中转发声明指向结构的指针

C++ 命名空间新手需要帮助

c++ - 使用 'equal to' 符号初始化期间的内存