Created
June 3, 2014 16:07
-
-
Save duckie/4833bc83976812ee6d95 to your computer and use it in GitHub Desktop.
Compute intersection of two lists - Method 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <unordered_set> | |
#include <list> | |
#include <algorithm> | |
using namespace std; | |
list<string> compare_list_warning(list<string> const& list_one, list<string> const& list_two) | |
{ | |
list<string> const& small_list = list_one.size() < list_two.size() ? list_one : list_two; | |
list<string> const& big_list = list_one.size() < list_two.size() ? list_two : list_one; | |
list<string> duplicates; | |
unordered_set<string> duplicate_finder; | |
duplicate_finder.insert(begin(small_list), end(small_list)); | |
copy_if(begin(big_list), end(big_list), back_inserter(duplicates), [&](string const& v) { return (duplicate_finder.find(v) != end(duplicate_finder)); }); | |
return duplicates; | |
} | |
int main() { | |
list<string> common_names = compare_list_warning({"Roger", "Marcel", "Camille", "Hubert"}, {"Huguette", "Cunegond", "Marcelle", "Camille"}); | |
for(string const& common : common_names) { | |
std::cout << "Common element: " << common << "\n"; | |
} | |
std::cout << std::flush; | |
return 0; | |
} |
Hi AK_
I'm sorry, I only saw you comment right now, it does not appear in the regular github notification hub :p
The copy_if is just another way of writing the same thing than you : it iterates over the first collection and pushes the elements that satisfy the given condition back the second one (hence the back_inserter). The condition is provided as a function, here written as a lambda.
Did the code modification on SO, its waiting for peer review
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi this is AK_, I really loved the way you optimized my code and used set instead of unordered_map since we dont really care about the stored values. Could you please explain line 16:
copy_if
?Also can you edit my code on SO so we can accept it as an answer..