stl向量
Given two vectors and we have to find their common elements.
给定两个向量,我们必须找到它们的共同元素。
寻找两个向量之间的共同元素 (Finding common elements between two vectors)
To find common elements between two vectors, we can use set_intersection() function, it accepts the iterators of both vectors pointing to the starting and ending ranges and an iterator of result vector (in which we store the result) pointing to the starting position and returns an iterator pointing to the end of the constructed range.
要找到两个向量之间的公共元素 ,我们可以使用set_intersection()函数 ,该函数接受两个向量的迭代器,这些迭代器都指向起始和结束范围,并且接受结果向量的迭代器(我们在其中存储结果)并指向起始位置,并且返回指向构造范围末端的迭代器。
Note: To use vector – include <vector> header, and to use set_intersection() function – include <algorithm> header or we can simply use <bits/stdc++.h> header file.
注意:要使用vector –包含<vector>头文件,而要使用set_intersection()函数 –包含<algorithm>头文件,或者我们可以简单地使用<bits / stdc ++。h>头文件。
Syntax:
句法:
std::set_intersection(
iterator start1, iterator end1,
iterator start1, iterator end1,
iterator start3);
Here, iterator start1, iterator end1 – are the iterators pointing to the starting and ending position of first vector, iterator start2, iterator end2 – are the iterators pointing to the starting and ending position of second vector, and iterator start3 – is an iterator pointing to the starting position of the result vector.
在这里, 迭代器start1,迭代器end1 –是指向第一个向量的开始和结束位置的迭代器,迭代器start2,迭代器end2 –是指向第二个向量的起始和结束位置的迭代器 , 迭代器start3 –是迭代器指向到结果向量的起始位置。
C ++ STL程序查找两个向量的公共元素 (C++ STL program to find the common elements of two vectors )
//C++ STL program to find common elements
//between two Vectors
#include <bits/stdc++.h>
using namespace std;
int main()
{
//vectors
vector<int> v1 = { 10, 20, 5, 40, 2, 30 };
vector<int> v2 = { 100, 10, 20, 30, 200, 300 };
//sorting the vectors
sort(v1.begin(), v1.end());
sort(v2.begin(), v2.end());
// Print the vectors
cout << "v1: ";
for (int x : v1)
cout << x << " ";
cout << endl;
cout << "v2: ";
for (int x : v2)
cout << x << " ";
cout << endl;
//declaring result vector to
//store the common elements
vector<int> v3(v1.size() + v2.size());
//iterator to store return type
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;
}
Output
输出量
v1: 2 5 10 20 30 40
v2: 10 20 30 100 200 300
Common elements v3: 10 20 30
翻译自: https://www.includehelp.com/stl/find-common-elements-between-two-vectors.aspx
stl向量