首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取向量对的range-v3交集

获取向量对的range-v3交集
EN

Stack Overflow用户
提问于 2019-12-04 02:06:01
回答 1查看 197关注 0票数 1

我想得到两个成对向量的交集。我可以使用stl,它使用默认的比较器(?-如果我写错了,请纠正我)。

代码语言:javascript
复制
std::vector<std::pair<int, int>> pathWire1 = {{1,1}, {2,2}, {3,3}};
std::vector<std::pair<int, int>> pathWire2 = { {2,2}, {0,0}};
std::vector<std::pair<int,int>> res;

std::sort(pathWire1.begin(), pathWire1.end());
std::sort(pathWire2.begin(), pathWire2.end());
std::set_intersection(pathWire1.begin(), pathWire1.end(),
                        pathWire2.begin(), pathWire2.end(),
                        std::back_inserter(res));

//res contains {2,2}

充其量我想用ranges来实现:

代码语言:javascript
复制
ranges::sort(pathWire1);
ranges::sort(pathWire2);
ranges::view::set_intersection(pathWire1, pathWire2);
//ranges::view::set_intersection(pathWire1, pathWire2, std::back_inserter(res);

我尝试遵循这个documentation,但是我不能编译它,因为模板无法专门化:

代码语言:javascript
复制
error C2672: 'operator __surrogate_func': no matching overloaded function found

我需要提供自定义的比较器吗?我在编译ranges::sort时也遇到了问题。是因为std::vector专用于非平凡类型std::pair

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-04 05:55:59

ranges::view::set_intersection以新范围(在本例中是一个新视图)的形式返回结果。请参阅tests如何使用该功能。

示例:

代码语言:javascript
复制
using IntPair = std::pair<int,int>;
using IntPairVector = std::vector<IntPair>;

IntPairVector pathWire1 = {{1,1}, {2,2}, {3,3}};
IntPairVector pathWire2 = { {2,2}, {0,0}};

ranges::sort(pathWire1);
ranges::sort(pathWire2);
auto res = ranges::view::set_intersection(pathWire1, pathWire2);

for(auto&& p : res)
    std::cout << p.first << ' ' << p.second << '\n';

// prints 2 2

LIVE DEMO

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59162970

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档