简体   繁体   中英

Get range-v3 intersection of vector of pairs

I want to get an intersection of two vectors of pairs. I can do it with the stl which uses the default comparator (? - correct me if I word it wrong).

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}

At best I wanted to do it with ranges:

ranges::sort(pathWire1);
ranges::sort(pathWire2);
ranges::view::set_intersection(pathWire1, pathWire2);
//ranges::view::set_intersection(pathWire1, pathWire2, std::back_inserter(res);

I tried to follow this documentation however I cannot get it to compile, because the template fails to specialize:

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

Do I need to provide custom comparator? I had problems with compiling ranges::sort as well. Is it because std::vector is specialized for non-trivial type std::pair ?

ranges::view::set_intersection returns the result as a new range (in this case, a new view). See the tests how to use that functionality.

Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM