2026-09-30
by_length.cpp
#include <iostream>
#include <set>
#include <string>
struct ByLength {
bool operator()(const std::string& a, const std::string& b) const {
return a.size() < b.size();
}
};
int main() {
std::set<std::string, ByLength> words;
for (const char* w : {"pear", "fig", "plum", "kiwi", "banana"}) {
words.insert(w);
}
for (const auto& w : words) {
std::cout << w << ' ';
}
std::cout << words.size() << '\n';
}
これは何を出力するでしょうか?
Answer
fig pear banana 3 です。
std::set は、2つの要素が同じかどうかを == ではなく比較関数で決めます。comp(a, b) と comp(b, a) がどちらも偽なら、a と b は等価とみなされます。ByLength は長さしか比べないので、長さが同じ文字列はすべて等価です。
"pear" が入ったあと、同じ4文字の "plum" と "kiwi" には等価な要素がすでにあるので、insert は何もしません。残るのは先に入った "pear" と、3文字の "fig"、6文字の "banana" の3つで、比較関数どおり短い順に並びます。