LoginSignup
4
4

More than 5 years have passed since last update.

指定したキーでソートするstd::sort

Last updated at Posted at 2014-10-03

std::sortの引数を短くしたい。毎回こういうのを書くのはちょっと面倒。

std::sort(idols.begin(), idols.end(),
  [](const Idol& lhs, const Idol& rhs){ return lhs.production_id < rhs.production_id; });

たいていの場合、ソート範囲はコンテナ全体で、比較するキーの抽出方法は比較演算子の左右で同じ、なので下記のラップ関数sort_byを書いてみた。

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

template<
  typename Inputs,
  typename Functor,
  typename T = typename Inputs::value_type>
void sort_by(Inputs& inputs, Functor f) {
  std::sort(std::begin(inputs), std::end(inputs),
    [&f](const T& lhs, const T& rhs){ return f(lhs) < f(rhs); });
}

struct Idol {
  std::string name;
  int production_id;
};

int main() {
  std::vector<Idol> idols = {
    {"Takane", 961},
    {"Kotori", 765},
    {"Mai",    876}
  };

  sort_by(idols, [](const Idol& idol){ return idol.production_id; });

  for (const auto& idol : idols) {
    std::cout << idol.name << std::endl;
  }

  return 0;
}

実行結果:[Wandbox]三へ( へ՞ਊ ՞)へ ハッハッ

Kotori
Mai
Takane
4
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4