【问题标题】:Get range-v3 intersection of vector of pairs获取对向量的 range-v3 交集
【发布时间】:2019-12-03 18:06:01
【问题描述】:

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

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::sort(pathWire1);
ranges::sort(pathWire2);
ranges::view::set_intersection(pathWire1, pathWire2);
//ranges::view::set_intersection(pathWire1, pathWire2, std::back_inserter(res);

我尝试关注这个documentation,但是我无法编译它,因为模板无法专门化:

error C2672: 'operator __surrogate_func': no matching overloaded function found

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

【问题讨论】:

标签: c++ c++17 range-v3


【解决方案1】:

ranges::view::set_intersection 将结果作为新范围返回(在本例中为新视图)。请参阅tests 如何使用该功能。

例子:

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

【讨论】:

  • 提供的示例适用于 wandbox 和其他在线编译器。但是在我的本地构建中,我使用的是ranges-v3 0.9.1,但我仍然无法编译它。我使用 MSVC 版本 19.23.28107 在 Windows 下构建。有什么建议吗?
  • 查看这篇关于 MSVC 的博文:devblogs.microsoft.com/cppblog/…。简而言之,使用vcpkg 安装range-v3,因为需要进行一些修改才能与MSVC 编译。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多