ようこそ、授業があります
Class test{
string a;
string b;
}
主に
vector<test> t;
そして、ファイルでソートする方法は?ASC と DESC をソートしますか? このソートを行う方法がわかりません
std::sort
カスタム コンパレータで使用します。
bool less_by_a(const test& lhs, const test& rhs)
{
return lhs.a < rhs.a;
}
それから
#include <algorithm>
...
std::sort(t.begin(), t.end(), less_by_a);
a
同様に、バリアントによるより大なりについても同様です。
次のようなユニバーサルコンパレータを書くことができます:
template <typename T, typename S, template <typename> class L>
struct compare : public std::binary_function <const S &, const S &, bool> {
compare (T typename S::* f) : f (f) { }
bool operator () (const S & lhs, const S & rhs) const {
return L <T> ().operator () (lhs.*f, rhs.*f);
}
private:
T typename S::* f;
};
template <template <typename> class L, typename T, typename S>
compare <T, S, L> make_compare (T typename S::* f) {
return compare <T, S, L> (f);
}
そしてそれを使用します:
std::sort (t.begin (), t.end (), make_compare <std::less> (& test::a));
ただし、「test::a」フィールドは公開する必要があります。