📌  相关文章
📜  如何在C++中使用STL在两个数组之间查找公共元素?

📅  最后修改于: 2021-05-30 14:12:51             🧑  作者: Mango

给定两个数组,请使用C++中的STL查找这两个数组之间的公共元素。

例子:

Input: 
arr1[] = {1, 45, 54, 71, 76, 12}, 
arr2[] = {1, 7, 5, 4, 6, 12}
Output: {1, 12}

Input: 
arr1[] = {1, 7, 5, 4, 6, 12}, 
arr2[] = {10, 12, 11}
Output: {1, 4, 12}

方法:可以通过STL中提供的set_intersection()函数找到常见元素。

句法:

set_intersection (InputIterator1 first1, InputIterator1 last1,
           InputIterator2 first2, InputIterator2 last2,
           OutputIterator result);
// C++ program to find common elements
// between two Arrays using STL
  
#include 
using namespace std;
  
int main()
{
  
    // Get the array
    int arr1[] = { 1, 45, 54, 71, 76, 12 };
    int arr2[] = { 1, 7, 5, 4, 6, 12 };
  
    // Compute the sizes
    int n1 = sizeof(arr1) / sizeof(arr1[0]);
    int n2 = sizeof(arr2) / sizeof(arr2[0]);
  
    // Sort the arrays
    sort(arr1, arr1 + n1);
    sort(arr2, arr2 + n2);
  
    // Print the array
    cout << "First Array: ";
    for (int i = 0; i < n1; i++)
        cout << arr1[i] << " ";
    cout << endl;
  
    cout << "Second Array: ";
    for (int i = 0; i < n2; i++)
        cout << arr2[i] << " ";
    cout << endl;
  
    // Initialise a vector
    // to store the common values
    // and an iterator
    // to traverse this vector
    vector v(n1 + n2);
    vector::iterator it, st;
  
    it = set_intersection(arr1, arr1 + n1,
                          arr2, arr2 + n2,
                          v.begin());
  
    cout << "\nCommon elements:\n";
    for (st = v.begin(); st != it; ++st)
        cout << *st << ", ";
    cout << '\n';
  
    return 0;
}
输出:
First Array: 1 12 45 54 71 76 
Second Array: 1 4 5 6 7 12 

Common elements:
1, 12,
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”