C++: Using Sets as Map Keys with Custom Comparator
To use a set as a map key in C++, you need to define a custom comparator for the set. This comparator will be responsible for determining the order of sets during comparison. Here's a detailed example:
#include <iostream>
#include <set>
#include <map>
using namespace std;
struct SetComparator {
bool operator()(const set<int>& a, const set<int>& b) const {
if (a.size() < b.size()) {
return true;
} else if (a.size() > b.size()) {
return false;
} else {
return lexicographical_compare(a.begin(), a.end(), b.begin(), b.end());
}
}
};
int main() {
map<set<int>, int, SetComparator> m;
set<int> s1 = {1, 2, 3};
set<int> s2 = {2, 3, 4};
set<int> s3 = {1, 2, 4};
m[s1] = 10;
m[s2] = 20;
m[s3] = 30;
for (auto& p : m) {
for (auto& x : p.first) {
cout << x << ' '; // Replaced double quote with single quote
}
cout << '-> ' << p.second << endl;
}
return 0;
}
Explanation:
SetComparatorstruct: This structure defines the comparison function for sets. Theoperator()overload is responsible for comparing two sets.- Comparison Logic:
- First, the sizes of the sets are compared. If one set is smaller, it is considered less than the other.
- If the sizes are equal, the
lexicographical_comparefunction is used to compare the elements of the sets in lexicographic order. This means elements are compared one by one, and the set with a lexicographically smaller element at the first difference is considered less.
mapDeclaration: Themapis declared using theSetComparatorstruct as the third template parameter, ensuring that theSetComparatoris used for key comparison.- Inserting Elements: Sets
s1,s2, ands3are used as keys for the map, and values are assigned accordingly. - Iteration and Output: The code iterates over the map, printing each key (set) and its associated value.
This approach allows you to effectively use sets as keys in C++ maps by customizing the comparison process for sets.
Note: The lexicographical_compare function is part of the <algorithm> header file, ensuring proper inclusion for this functionality.
原文地址: https://www.cveoy.top/t/topic/ojQf 著作权归作者所有。请勿转载和采集!