Skip to content

Instantly share code, notes, and snippets.

@Liam0205
Created December 13, 2017 11:11
Show Gist options
  • Select an option

  • Save Liam0205/0639d8651ef359149f7c41d75c9807a9 to your computer and use it in GitHub Desktop.

Select an option

Save Liam0205/0639d8651ef359149f7c41d75c9807a9 to your computer and use it in GitHub Desktop.
Set intersection and union, supporting std::unordered_set
$ ./a.out
4 5
1 2 3 4 5 6 7 8
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
#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