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