equal elements in two arrays in c++

C++ Code to Find Equal Elements in Two Arrays

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    std::vector<int> arr1 = {1, 2, 3, 4, 5};
    std::vector<int> arr2 = {3, 4, 5, 6, 7};

    std::sort(arr1.begin(), arr1.end());
    std::sort(arr2.begin(), arr2.end());

    std::vector<int> common;

    std::set_intersection(arr1.begin(), arr1.end(), arr2.begin(), arr2.end(), std::back_inserter(common));

    for (int num : common) {
        std::cout << num << " ";
    }

    return 0;
}

Explanation

  • Include necessary libraries:
  • #include <iostream> for input/output operations.
  • #include <algorithm> for sorting arrays and finding intersections.
  • #include <vector> for using vectors to store arrays.

  • Define the main function:

  • Create two vectors, arr1 and arr2, with some initial values.

  • Sort the arrays:

  • Use std::sort to sort both arr1 and arr2 in ascending order.

  • Find common elements:

  • Create a new vector, common, to store the common elements.
  • Use std::set_intersection to find the common elements between arr1 and arr2 and store them in the common vector.

  • Output the common elements:

  • Iterate through the common vector and print each common element.

  • Return 0 to indicate successful execution.