This post will discuss how to get the difference between two vectors in C++. For vectors x and y, the solution returns all elements that are present in x, but not in y.

The recommended approach to the difference between two vectors in C+ is using the standard algorithm std::set_difference. It constructs a sorted range with the set difference of the specified sorted ranges.

 
The following code example demonstrates the invocation of this function. Since std::set_difference takes the sorted range, we must sort both vectors. To avoid any modifications to the vector, perform sorting on the copy of both vectors.

Download  Run Code

Output:

4 6

 
To get the function return a set, use std::inserter since std::back_inserter doesn’t work on a set.

Download  Run Code

Output:

6 4

That’s all about getting the difference between two vectors in C++.