Created
December 13, 2017 11:11
-
-
Save Liam0205/0639d8651ef359149f7c41d75c9807a9 to your computer and use it in GitHub Desktop.
Set intersection and union, supporting std::unordered_set
This file contains hidden or 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
| $ ./a.out | |
| 4 5 | |
| 1 2 3 4 5 6 7 8 |
This file contains hidden or 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
| namespace setop { | |
| template <typename Set, typename Key = typename Set::value_type> | |
| static inline Set | |
| set_union(const Set& lhs, const Set& rhs) { | |
| Set uset{lhs}; | |
| uset.insert(rhs.begin(), rhs.end()); | |
| return std::move(uset); | |
| } | |
| template <typename Set, typename Key = typename Set::value_type> | |
| static inline Set | |
| set_intersection(const Set& lhs, const Set& rhs) { | |
| if (lhs.size() <= rhs.size()) { | |
| Set iset; | |
| for (const Key& key : lhs) { | |
| if (rhs.count(key) > 0) { | |
| iset.insert(key); | |
| } | |
| } | |
| return std::move(iset); | |
| } else { | |
| return set_intersection(rhs, lhs); | |
| } | |
| } | |
| } // namespace setop |
This file contains hidden or 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 <unordered_set> | |
| #include "set_operator.hpp" | |
| int main() { | |
| std::unordered_set<int> lhs{1, 2, 3, 4, 5}; | |
| std::unordered_set<int> rhs{4, 5, 6, 7, 8}; | |
| for (const auto& e : setop::set_intersection(lhs, rhs)) { | |
| std::cout << e << ' '; | |
| } | |
| std::cout << '\n'; | |
| for (const auto& e : setop::set_union(lhs, rhs)) { | |
| std::cout << e << ' '; | |
| } | |
| std::cout << '\n'; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment