在本教程中,我们将讨论一个程序,以了解如何使用C ++中的STL在两个向量之间查找公共元素。
为了找到两个给定向量之间的公共元素,我们将使用set_intersetion()方法。
#include <bits/stdc++.h> using namespace std; int main(){ //defining the vectors vector<int> vector1 = { 1, 45, 54, 71, 76, 12 }; vector<int> vector2 = { 1, 7, 5, 4, 6, 12 }; sort(vector1.begin(), vector1.end()); sort(vector2.begin(), vector2.end()); cout << "First Vector: "; for (int i = 0; i < vector1.size(); i++) cout << vector1[i] << " "; cout << endl; cout << "Second Vector: "; for (int i = 0; i < vector2.size(); i++) cout << vector2[i] << " "; cout << endl; vector<int> v(vector1.size() + vector2.size()); vector<int>::iterator it, st; //finding the common elements it = set_intersection(vector1.begin(), vector1.end(), vector2.begin(), vector2.end(), v.begin()); cout << "\nCommon elements:\n"; for (st = v.begin(); st != it; ++st) cout << *st << ", "; cout << '\n'; return 0; }
输出结果
First Vector: 1 12 45 54 71 76 Second Vector: 1 4 5 6 7 12 Common elements: 1, 12,