如何比较同一对象的两个向量并获取其他元素

时间:2021-07-16 16:14:21

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.

我想比较两个对象向量元素并相应地获取同一对象的其他向量元素。例如,对象有一个向量; foo1.a = [4 2 1 3] foo2.a = [2 1 4]我想找到相同的元素然后相应地得到其他向量包含,例如foo1.b = [8 8 2 10]和foo2.b = [8 2 8]根据我从foo.a得到的调查结果。我试图在循环中比较两个向量然后得到相同,但我失败了。

1 个解决方案

#1


3  

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:

使用set_intersection查找公共元素:

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:

使用set_difference查找唯一元素:

std::vector<int> vd;
std::set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), vd.begin()); // {3}

#1


3  

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:

使用set_intersection查找公共元素:

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:

使用set_difference查找唯一元素:

std::vector<int> vd;
std::set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), vd.begin()); // {3}