order_by

order_by - std-proposals

ソートするときに、左辺と右辺を比較するラムダ式を書くのがめんどくさいので、「どの要素を比較対象とするか」だけを書きたい、という目的のためのラッパー、order_by

template <class F>
struct OrderBy {
    F f;

    template <class T>
    bool operator()(const T& x, const T& y) const
    {
        return f(x) < f(y);
    }
};

template <class F>
OrderBy<F> order_by(F f)
{
    return {f};
}

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

int main()
{
    std::vector<std::pair<int, std::string>> v = {
        {3, "Alice"},
        {1, "Bob"},
        {4, "Carol"}
    };

    // firstをキーにして並び替え
    std::sort(v.begin(), v.end(), order_by([](auto x) { return x.first; }));

    for (const auto& x : v) {
        std::cout << x.first << std::endl;
    }
}

出力:

1
3
4

前に全く同じのを書いた気がする。

order_byという名前はデータベースっぽすぎる気もするので、もうちょっと考えた方がいいかもしれない。そんなこともないかもしれない。

コメント