Last active
October 8, 2020 05:55
-
-
Save KmolYuan/3a43d6fe8f7d4d246fdc8ff167733eb7 to your computer and use it in GitHub Desktop.
A swappable pair container for STL set or map.
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 <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