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:

  1. SetComparator struct: This structure defines the comparison function for sets. The operator() overload is responsible for comparing two sets.
  2. 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_compare function 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.
  3. map Declaration: The map is declared using the SetComparator struct as the third template parameter, ensuring that the SetComparator is used for key comparison.
  4. Inserting Elements: Sets s1, s2, and s3 are used as keys for the map, and values are assigned accordingly.
  5. 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.

C++: Using Sets as Map Keys with Custom Comparator

原文地址: https://www.cveoy.top/t/topic/ojQf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录