Home > Enterprise >  I am trying to loop inserting elements into a set if they intersect, but it isn't giving me wha
I am trying to loop inserting elements into a set if they intersect, but it isn't giving me wha

Time:10-08

all and all2 are both string sets. all is filled with actors in movie1, and all2 is empty. my loop is supposed to check if an actor in movie2 is also in movie1, and if they are then to insert that actor in all2. However my code is just outputting all the actors in movie2.

all = imdb.find_actors_in_a_movie(matchedMovie1);
for (auto i = actors_in_movie2.begin(); i != actors_in_movie2.end(); i  )
{
    if (all.count(*m) > 0)
    {
        all2.insert(*m);
    }
}    

all holds Christopher Walken, Leonardo DiCaprio, Martin Sheen, Tom Hanks

actors_in_movie2 holds Greg Kinnear, Meg Ryan, Parker Posey, Tom Hanks

The output I receive is Greg Kinnear, Meg Ryan, Parker Posey, Tom Hanks.

It should only be outputting Tom Hanks.

CodePudding user response:

Instead of writing a loop, use std::set_intersection.

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

int main()
{
    std::set<std::string> all = {"Joe", "Jack", "Mary", "Frank"};
    std::set<std::string> actors_in_movie2 = {"James", "Jack", "Philip", "Frank"};
    std::set<std::string> all2;
    std::set_intersection(actors_in_movie2.begin(),
                        actors_in_movie2.end(),
                        all.begin(),
                        all.end(),
                        std::inserter(all2, all2.end()));

   for (auto& n : all2)
      std::cout << n << "\n";                            
}

Output:

Frank
Jack

Since a std::set stores the names sorted, and std::set_intersection requires a sorted sequence to work correctly, using std::set_intersection is a ready-made solution.

Live Example using your input

  •  Tags:  
  • c
  • Related