How to Find the Difference of Two Vectors in C++?
Last Updated :
21 Feb, 2024
In C++, vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted. In this article, we will learn how to get the difference between two vectors in C++.
Example
Input:
vec1 = { 1, 2, 3, 4, 5 };
vec2 = { 3, 4, 5, 6, 7 };
Output:
Difference: {1, 2}
Finding the Difference Between Two Vectors
The difference between two vectors refers to the elements of the first vector that are not in the second vector.
In C++, the std::set_difference function from the <algorithm> header can be used to find the difference between two vectors. The set_difference algorithm takes two sorted ranges and outputs a new range containing the elements present in the first range but not in the second range.
Syntax of std::set_difference
set_difference(first1, last1, first2, last2, d_first);
- first1, last1: The input range of the first vector.
- first2, last2: The input range of the second vector.
- d_first: The output iterator to the beginning of the resulting difference vector.
C++ Program to Find the Difference of Two Vectors
C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > vec1 = { 1, 2, 3, 4, 5 };
vector< int > vec2 = { 3, 4, 5, 6, 7 };
sort(vec1.begin(), vec1.end());
sort(vec2.begin(), vec2.end());
vector< int > difference;
set_difference(vec1.begin(), vec1.end(), vec2.begin(),
vec2.end(), back_inserter(difference));
cout << "Difference: " ;
for ( const auto & element : difference) {
cout << element << " " ;
}
cout << endl;
return 0;
}
|
Time Complexity: O(NlogN + MlogM), where N and M are the sizes of the input vectors.
Auxiliary Space: O(N + M)
Share your thoughts in the comments
Please Login to comment...