The std::ranges::set_symmetric_difference()
algorithm finds elements that are in either of two sets but not in both. This operation can be very useful in various practical scenarios where you need to identify differences between two datasets.
Imagine you have two lists of students from different classes, and you want to find out which students are unique to each class:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<std::string> classA{
"Alice", "Bob", "Charlie"};
std::vector<std::string> classB{
"Bob", "David", "Eve"};
std::vector<std::string> uniqueStudents;
uniqueStudents.resize(
classA.size() + classB.size());
std::sort(classA.begin(), classA.end());
std::sort(classB.begin(), classB.end());
auto [AEnd, BEnd, SymDiffEnd] =
std::ranges::set_symmetric_difference(
classA, classB, uniqueStudents.begin());
uniqueStudents.erase(
SymDiffEnd, uniqueStudents.end());
for (const auto& student : uniqueStudents) {
std::cout << student << "\n";
}
}
Alice
Charlie
David
Eve
Another practical use is comparing two sets of files in directories to find which files are unique to each directory:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<std::string> dirA{
"file1.txt", "file2.txt", "file3.txt"};
std::vector<std::string> dirB{
"file2.txt", "file4.txt", "file5.txt"};
std::vector<std::string> uniqueFiles;
uniqueFiles.resize(dirA.size() + dirB.size());
std::sort(dirA.begin(), dirA.end());
std::sort(dirB.begin(), dirB.end());
auto [AEnd, BEnd, SymDiffEnd] =
std::ranges::set_symmetric_difference(
dirA, dirB, uniqueFiles.begin());
uniqueFiles.erase(SymDiffEnd, uniqueFiles.end());
for (const auto& file : uniqueFiles) {
std::cout << file << "\n";
}
}
file1.txt
file3.txt
file4.txt
file5.txt
In inventory management, you might want to find products that are unique to each warehouse:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<std::string> warehouseA{
"item1", "item2", "item3"};
std::vector<std::string> warehouseB{
"item2", "item4", "item5"};
std::vector<std::string> uniqueItems;
uniqueItems.resize(
warehouseA.size() + warehouseB.size());
std::sort(warehouseA.begin(), warehouseA.end());
std::sort(warehouseB.begin(), warehouseB.end());
auto [AEnd, BEnd, SymDiffEnd] =
std::ranges::set_symmetric_difference(
warehouseA, warehouseB, uniqueItems.begin());
uniqueItems.erase(SymDiffEnd, uniqueItems.end());
for (const auto& item : uniqueItems) {
std::cout << item << "\n";
}
}
item1
item3
item4
item5
These examples demonstrate how std::ranges::set_symmetric_difference()
can be applied to real-world scenarios where comparing two sets for unique elements is necessary.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to set algorithms, and how to implement them using the C++ standard library