-2

ようこそ、授業があります

Class test{
   string a;
   string b;
}

主に

vector<test> t;

そして、ファイルでソートする方法は?ASC と DESC をソートしますか? このソートを行う方法がわかりません

4

4 に答える 4

8

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同様に、バリアントによるより大なりについても同様です。

于 2013-10-18T08:55:31.987 に答える
0

次のようなユニバーサルコンパレータを書くことができます:

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」フィールドは公開する必要があります。

于 2013-10-18T09:24:28.540 に答える