Reputation: 47
I want to compare two object vector element and get the other vector elements of the same object accordingly. For example object has a vector;
foo1.a=[4 2 1 3] foo2.a=[2 1 4]
I want to find same elements and then get the other vectors containment correspondingly such as foo1.b=[8 8 2 10]
and foo2.b=[8 2 8]
according to findings I get from foo.a
. I tried to compare two vectors in the loops and then get the same, but I failed.
Upvotes: 2
Views: 2843
Reputation: 14622
Given two vectors:
std::vector<int> v1; // {4, 2, 1, 3};
std::vector<int> v2; // {2, 1, 4};
First, sort
the two vectors so that it's 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 elements:
std::vector<int> vd;
std::set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), vd.begin()); // {3}
Upvotes: 4