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

How to compare two vectors of a same object and get other elements

本文关键字:两个 向量 元素 其他 比较 何比较 对象      更新时间:2023-10-16

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

给定两个向量:

std::vector<int> v1; // {4, 2, 1, 3};
std::vector<int> v2; // {2, 1, 4};

首先,sort两个矢量,这样就很容易找到共同的元素:

std::sort(v1); // {1, 2, 3, 4}
std::sort(v2); // {1, 2, 4}

使用set_intersection查找常见元素:

std::vector<int> vi;
std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), vi.begin()); // {1, 2, 4}

使用set_difference查找唯一元素:

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