With the help of this tutorial we will understand how we can find some common elements from an array .
There are several methods but we will use bitwise operations and set intersection algos here.
I know you are getting excited for this insightful learning of how can we find common elements from an array
So lets get started
Finding common elements from an array in C++
We use bitwise operations when we have a limited range of numbers .
Here we use operations like bitsets to represent the presence of elements and then perform bitwise AND operation to find common elements. This approach is efficient but requires a limited range of numbers.
Some standard libraries provide set intersection algorithms like std::set_intersection
, which can efficiently find common elements between two sorted ranges. This approach is particularly useful when the input arrays are already sorted.
LET”S put aside this theory portion and give our boost to our understanding by means of a code:
#include <iostream>
#include <unordered_set>
#include <vector>
std::vector<int> findCommonElements(const std::vector<int>& arr1, const std::vector<int>& arr2) {
std::unordered_set<int> set;
std::vector<int> commonElements;
for (int num : arr1) {
set.insert(num);
}
for (int num : arr2) {
if (set.find(num) != set.end()) {
commonElements.push_back(num);
}
}
return commonElements;
}
int main() {
std::vector<int> arr1 = {1, 2, 3, 4, 5};
std::vector<int> arr2 = {3, 4, 5, 6, 7};
std::vector<int> commonElements = findCommonElements(arr1, arr2);
std::cout << "Common elements are: ";
for (int num : commonElements) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
this code gives the output as :
:
Common elements are: 3 4 5