歡迎排序, 我有類的C++ Vector和由日提交
Class test{
string a;
string b;
}
在主
vector<test> t;
以及如何排序由提起類?整理ASC和DESC? 我不知道知道如何使用自定義比較這樣soritng
歡迎排序, 我有類的C++ Vector和由日提交
Class test{
string a;
string b;
}
在主
vector<test> t;
以及如何排序由提起類?整理ASC和DESC? 我不知道知道如何使用自定義比較這樣soritng
使用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
變種。
使用內部操作<
爲class test
:
class test {
//..
string a;
strint b;
//...
bool operator<(const test& t) const
{
return a < t.a;
}
//..
};
然後,
std::sort(t.begin(),t.end());
我認爲使用自定義比較器好得多,因爲這個類似乎沒有明顯的比較默認條件(比如它可能是'b'而不是'a')。 – Gorpik
有標準算法的std ::排序C++中。它可以接受一個指定排序順序的謂詞。
所以以按升序矢量可以寫
std::sort(t.begin(), t.end(), [](const test &t1, const test &t2) { return (t1.a < t2.a); });
提供的數據成員一個具有公共訪問控制(在你的榜樣擁有私人的訪問控制)。
要按從高到低的順序矢量你根本扭轉的條件
std::sort(t.begin(), t.end(), [](const test &t1, const test &t2) { return (t2.a < t1.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」字段必須公開。
到目前爲止您嘗試了什麼? –