Get difference between two vectors in C++
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <iostream> #include <vector> #include <algorithm> template<typename T> std::vector<T> findDiff(std::vector<T> x, std::vector<T> y) { // no-ref, no-const std::vector<T> diff; std::sort(x.begin(), x.end()); std::sort(y.begin(), y.end()); std::set_difference(x.begin(), x.end(), y.begin(), y.end(), std::back_inserter(diff)); return diff; } int main() { std::vector<int> x = {1, 3, 5, 6, 7, 4, 8}; std::vector<int> y = {1, 2, 3, 5, 7, 8}; std::vector<int> diff = findDiff(x, y); for (int &i: diff) { std::cout << i << ' '; } return 0; } |
Output:
4 6
To get the function return a set, use std::inserter since std::back_inserter doesn’t work on a set.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#include <iostream> #include <vector> #include <algorithm> #include <unordered_set> template<typename T> std::unordered_set<T> findDiff(std::vector<T> x, std::vector<T> y) { // no-ref, no-const std::unordered_set<T> diff; std::sort(x.begin(), x.end()); std::sort(y.begin(), y.end()); std::set_difference(x.begin(), x.end(), y.begin(), y.end(), std::inserter(diff, diff.begin())); return diff; } int main() { std::vector<int> x = {1, 3, 5, 6, 7, 6, 4, 8}; std::vector<int> y = {1, 2, 3, 5, 7, 8}; std::unordered_set<int> diff = findDiff(x, y); for (int i: diff) { std::cout << i << ' '; } return 0; } |
Output:
6 4
That’s all about getting the difference between two vectors in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)