Skip to content

Instantly share code, notes, and snippets.

@KmolYuan
Last active October 8, 2020 05:55
Show Gist options
  • Save KmolYuan/3a43d6fe8f7d4d246fdc8ff167733eb7 to your computer and use it in GitHub Desktop.
Save KmolYuan/3a43d6fe8f7d4d246fdc8ff167733eb7 to your computer and use it in GitHub Desktop.
A swappable pair container for STL set or map.
#include <iostream>
#include <set>
#include <map>
template<typename T>
struct SwappablePair {
T field1, field2;
inline auto operator==(const SwappablePair &rhs) const -> bool {
return (field1 == rhs.field1 && field2 == rhs.field2) ||
(field1 == rhs.field2 && field2 == rhs.field1);
}
inline auto operator!=(const SwappablePair &rhs) const -> bool {
return !this->operator==(rhs);
}
inline auto operator<(const SwappablePair &rhs) const -> bool {
return this->operator!=(rhs) && (field1 < rhs.field1 || field2 < rhs.field2);
}
};
int main() {
const auto s = std::set<SwappablePair<int>>
{{10, 20},
{20, 10},
{60, 20},
{10, 10}};
const auto m = std::map<SwappablePair<int>, bool>
{{{10, 20}, true},
{{20, 10}, false},
{{60, 20}, true},
{{10, 10}, false}};
// Show count
// 3
std::cout << s.size() << std::endl;
// Show all elements
// 10, 10
// 10, 20
// 60, 20
for (auto e : s)
std::cout << e.field1 << ", " << e.field2 << std::endl;
// 10, 10: 0
// 10, 20: 1
// 60, 20: 1
for (auto [k, v] : m)
std::cout << k.field1 << ", " << k.field2 << ": " << v << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment