给定两个数组,任务是我们使用C++中的STL查找在第一个数组中存在但在第二个数组中不存在的数字
例子:
Input: a[] = {1, 2, 3, 4, 5, 10}, b[] = {2, 3, 1, 0, 5}
Output: 4 10
Input:a[] = {4, 3, 5, 9, 11}, b[] = {4, 9, 3, 11, 10};
Output: 5
方法:在STL中,可以使用set_difference()方法查找“ AB”,其中A是第一个数组,B是第二个数组。
句法:
OutputIterator set_difference (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result);
下面是上述方法的实现:
// C++ simple program to
// find elements which are
// not present in second array
#include
using namespace std;
// Function for finding
// elements which are there
// in a[] but not in b[].
void findMissing(int a[], int b[],
int n, int m)
{
// Declare a vector to store the result
vector v(n + m);
// And an iterator to traverse the vector
vector::iterator it;
// Sort the given arrays
sort(a, a + n);
sort(b, b + m);
// Find the elements in a[]
// which are not in b[]
it = set_difference(a, a + n, b, b + m, v.begin());
// Now resize the vector to the existing count
v.resize(it - v.begin());
// Print the results
cout << "The elements in a[]"
<< " which are not in b[]:\n";
for (it = v.begin(); it != v.end(); ++it)
cout << *it << " ";
cout << endl;
}
// Driver code
int main()
{
int a[] = { 1, 2, 6, 3, 4, 5 };
int b[] = { 2, 4, 3, 1, 0 };
int n = sizeof(a) / sizeof(a[0]);
int m = sizeof(b) / sizeof(b[1]);
findMissing(a, b, n, m);
return 0;
}
输出:
The elements in a[] which are not in b[]:
5 6
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。