Jacob Adams
Jacob Adams

Reputation: 11

How to perform Set Operations in C++?

I am a second year student trying to complete a project assigned by a really crappy professor. She taught us how to perform set intersection and symmetric difference inside of Bash, but when it comes to C++ I am lost.

Attached is the code currently in my project. The context is that based on a given file, movies are imported and actors are found. I know my file is reading correctly, as I have tested it multiple ways.

Also attached is a copy of the way she describes set operations. Please help!

image

cout << "Actors in both movies are: " << endl;
set<string> intersect;

set_intersection(actors_in_movie1.begin(), actors_in_movie1.end(), actors_in_movie2.begin(), actors_in_movie2.end(), inserter(intersect, intersect.begin()));
for(auto j = intersect.begin(); j != intersect.end(); j++)
{
    cout << *j << endl;
}

Upvotes: 1

Views: 1316

Answers (1)

NicholasM
NicholasM

Reputation: 4673

If you sort your input ranges, you can use the std::set_union, std::set_intersection, and std::set_symmetric_difference algorithms in the algorithm header.

#include <algorithm>
#include <iterator>
#include <set>
#include <string>
#include <vector>

#include <cassert>

int main() {

    std::vector<std::string> a1{{"A", "B", "C"}};
    std::vector<std::string> a2{{"B", "C", "D", "F", "X"}};

    assert(std::is_sorted(a1.begin(), a1.end()));
    assert(std::is_sorted(a2.begin(), a2.end()));

    std::set<std::string> union_;
    std::set_union(a1.begin(), a1.end(), a2.begin(), a2.end(), 
                   std::inserter(union_, union_.begin()));

    std::set<std::string> intersection;
    std::set_intersection(a1.begin(), a1.end(), a2.begin(), a2.end(), 
                          std::inserter(intersection, intersection.begin()));

    std::set<std::string> symmetric_diff;
    std::set_symmetric_difference(a1.begin(), a1.end(), a2.begin(), a2.end(), 
                                  std::inserter(symmetric_diff, symmetric_diff.begin()));
}

Working example at https://ideone.com/dW9AkT :

a1: A, B, C, 
a2: B, C, D, F, X, 

union: A, B, C, D, F, X, 
intersection: B, C, 
symmetric_difference: A, D, F, X, 

Upvotes: 3

Related Questions