example3_custom_comparator.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <set>
#include <string>

struct CompareLength {
    bool operator()(const std::string& lhs, const std::string& rhs) const {
        return lhs.length() < rhs.length();
    }
};

int main() {
    std::set<std::string, CompareLength> words = {"apple", "banana", "cherry", "date"};

    for (const auto& word : words) {
        std::cout << word << " ";
    }
    std::cout << std::endl;

    return 0;
}
Back to set