给定两个向量,我们必须找到它们的共同元素。
为了找到两个向量之间的公共元素,我们可以使用set_intersection()函数,该函数接受两个向量的迭代器,这些迭代器都指向起始和结束范围,并且接受结果向量的迭代器(我们在其中存储结果)并指向起始位置,并且返回指向构造范围末端的迭代器。
注意:要使用vector –包含<vector>头文件,并使用set_intersection()函数–包含<algorithm>头文件,或者我们可以简单地使用<bits / stdc ++。h>头文件。
语法:
std::set_intersection( iterator start1, iterator end1, iterator start1, iterator end1, iterator start3);
在这里,迭代器start1,迭代器end1 –是指向第一个向量的开始和结束位置的迭代器,迭代器start2,迭代器end2 –是指向第二个向量的起始和结束位置的迭代器,迭代器start3 –是迭代器指向到结果向量的起始位置。
//使用C ++ STL程序查找常见元素
//在两个向量之间
#include <bits/stdc++.h>
using namespace std;
int main(){
//向量
vector<int> v1 = { 10, 20, 5, 40, 2, 30 };
vector<int> v2 = { 100, 10, 20, 30, 200, 300 };
//排序向量
sort(v1.begin(), v1.end());
sort(v2.begin(), v2.end());
//打印矢量
cout << "v1: ";
for (int x : v1)
cout << x << " ";
cout << endl;
cout << "v2: ";
for (int x : v2)
cout << x << " ";
cout << endl;
//将结果向量声明为
//存储常见元素
vector<int> v3(v1.size() + v2.size());
//用于存储返回类型的迭代器
vector<int>::iterator it, end;
end = set_intersection(
v1.begin(), v1.end(),
v2.begin(), v2.end(),
v3.begin());
cout << "Common elements v3: ";
for (it = v3.begin(); it != end; it++)
cout << *it << " ";
cout << endl;
return 0;
}输出结果
v1: 2 5 10 20 30 40 v2: 10 20 30 100 200 300 Common elements v3: 10 20 30