Skip to content

Instantly share code, notes, and snippets.

@piyo7
Last active August 29, 2015 14:07
Show Gist options
  • Save piyo7/50d2084389cd5fe7b9d7 to your computer and use it in GitHub Desktop.
Save piyo7/50d2084389cd5fe7b9d7 to your computer and use it in GitHub Desktop.
指定したキーでソートするstd::sort ref: http://qiita.com/piyo7/items/e23670cd89502680649c
std::sort(idols.begin(), idols.end(),
[](const Idol& lhs, const Idol& rhs){ return lhs.production_id < rhs.production_id; });
#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;
}
Kotori
Mai
Takane
Kotori
Mai
Takane
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment