How to Find Difference of Two Sorted Vectors in C++?
In C++, vectors are containers similar to arrays but unlike arrays, vectors can change their size dynamically during the insertion or deletion of elements. In this article, we will learn how we can find the difference between two sorted vectors in C++. The difference of two vectors is a vector that contains elements present in the first vector but not in the second.
Example:
Input:
myVector1 = {1, 2, 3, 4, 5}
myVector2 = { 3, 4, 5, 7, 8}
Output:
Difference of two vectors is {1, 2}
Find the Difference of Two Sorted Vectors in C++
We can easily find the difference between the two vectors using the std:: set_difference() method provided by the STL in C++. But the vectors should be sorted in increasing order so that the std::set_difference() can find the difference between them or else the behavior will be undefined.
C++ Program to Find the Difference of Two Sorted Vectors
C++
// C++ program Find the Difference of Two Vectors #include <algorithm> #include <iostream> #include <vector> using namespace std; int main() { // Initialize two input vectors vector< int > vec1 = { 10, 20, 3, 4, 5 }; vector< int > vec2 = { 3, 4, 5, 7, 8 }; // Print elements of both the vectors cout << "Element in Vector 1: " ; for ( auto num : vec1) { cout << num << " " ; } cout << endl; cout << "Element in Vector 2: " ; for ( auto num : vec2) { cout << num << " " ; } cout << endl; // Define a vector to store the difference vector< int > difference; // Find the difference of vec1 and vec2 set_difference(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), back_inserter(difference)); // Print the difference between the vectors cout << "Difference of two vectors is: " ; for ( auto element : difference) { cout << element << " " ; } return 0; } |
Element in Vector 1: 10 20 3 4 5 Element in Vector 2: 3 4 5 7 8 Difference of two vectors is: 10 20 3 4 5
Time Complexity: O(N) where N is the number of elements in both the vectors
Auxiliary Space: O(N)
Contact Us