I need get the intersection list between two vectors. And in my case vectors are vector of user type. So to get the number encapsulated I must use a comparer function.
Also I want to able get the intersection with a offSet. For example give two vectors {1,2,3,4,6,8} and {5, 7, 9,10} . Intersection with offSet 2 is { 3,8 } since 3 + 2 = 5 and 8 + 2 = 10.
I suppose the code below should work but instead {3,8} I am getting {3,6,8} . I couldn't figure out how to use comparer function of std::set_intersection. What am I missing?
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
struct A
{
A ( int in ) { a = in; }
int getNumber() { return a; }
bool operator< ( A rhs )
{
return this->a < rhs.a;
}
int a;
};
int main()
{
std::vector<A> v1{1,2,3,4,6,8};
std::vector<A> v2{5, 7, 9,10};
int offSet = 2;
auto lessThanWithOffset = [offSet]( A lhs, A rhs)
{
return lhs.getNumber() + offSet < rhs.getNumber();
};
std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
std::vector<A> v_intersection;
std::set_intersection(v1.begin(), v1.end(),
v2.begin(), v2.end(),
std::back_inserter(v_intersection), lessThanWithOffset);
for(auto n : v_intersection)
std::cout << n.getNumber() << ' ';
}
Aucun commentaire:
Enregistrer un commentaire