How to compare two vectors of the same object and get other elements
I want to compare two elements of an object vector and get other vector elements of the same object respectively. For example, an object has a vector; foo1.a=[4 2 1 3] foo2.a=[2 1 4]
I want to find the same elements and then get the corresponding wrapper of the other vectors, for example foo1.b=[8 8 2 10]
and foo2.b=[8 2 8]
according to the inferences I got from foo.a
. I tried to compare two vectors in loops and then get the same thing, but I failed.
source to share
For two vectors:
std::vector<int> v1; // {4, 2, 1, 3};
std::vector<int> v2; // {2, 1, 4};
First sort
two vectors to make it easy to find common elements:
std::sort(v1); // {1, 2, 3, 4}
std::sort(v2); // {1, 2, 4}
Use set_intersection
to find common elements:
std::vector<int> vi;
std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), vi.begin()); // {1, 2, 4}
Use set_difference
to find unique items:
std::vector<int> vd;
std::set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), vd.begin()); // {3}
source to share