Horje
How to Find the Difference of Two Vectors in C++?

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++

// CPP program to Find the Difference of Two Vectors Using
// set_difference
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
  
int main()
{
    // Step 2: Create and initialize the two vectors
    vector<int> vec1 = { 1, 2, 3, 4, 5 };
    vector<int> vec2 = { 3, 4, 5, 6, 7 };
  
    // Step 3: Sort both vectors
    sort(vec1.begin(), vec1.end());
    sort(vec2.begin(), vec2.end());
  
    // Step 4: Create a new vector to store the difference
    vector<int> difference;
  
    // Step 5: Use set_difference
    set_difference(vec1.begin(), vec1.end(), vec2.begin(),
                   vec2.end(), back_inserter(difference));
  
    // Step 6: Print the elements of the difference vector
    cout << "Difference: ";
    for (const auto& element : difference) {
        cout << element << " ";
    }
    cout << endl;
  
    return 0;
}
  
// This code is contributed by Susobhan Akhuli

Output

Difference: 1 2 

Time Complexity: O(NlogN + MlogM), where N and M are the sizes of the input vectors.
Auxiliary Space: O(N + M)




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Access Individual Characters in a C++ String? How to Access Individual Characters in a C++ String?
How to Convert an Enum to a String in C++? How to Convert an Enum to a String in C++?
How to Check if a Vector is Empty in C++? How to Check if a Vector is Empty in C++?
How to Find the Median of Array in C++? How to Find the Median of Array in C++?
How to Override a Base Class Method in a Derived Class in C++? How to Override a Base Class Method in a Derived Class in C++?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14