[英]C++: How to sort a vector of objects derived from class using one of its parameters
我正在嘗試對從項目中的類創建的對象向量進行排序。
我有兩個類 - Playlist 和 ListIndex,它們繼承自 List_base 類。 在 List_base 類中,我想按名稱對對象向量(播放列表或 ListIndex)進行排序。 name 屬性在 List_base 類中定義。 我嘗試使用 struct 或 function 來比較 name 字段並將其傳遞給 sort 函數。 我收到各種錯誤。 我是 C++ 的新手,很長一段時間都陷入這個錯誤
帶有比較函數的 List_base 排序方法
//the function should be able to get either Playlist vector
// or ListIndex vector (both inherits from List_base)
void List_base::sortList(vector<List_base> data) {
sort(data.begin(), data.end(), compFunc());
}
bool List_base::compFunc(List_base *a, List_base *b) {
return a->getName().compare(b->getName()) > 0;
}
name 字段在 List_base 類中聲明:
class List_base
{
public:
List_base(string name);
string getName();
void sortList(vector<List_base> data);
virtual ~List_base();
protected:
private:
string name;
bool compFunc(List_base *a, List_base *b);
};
我究竟做錯了什么? 我什至不能專注於一個特定的錯誤。 我也試過鑄造,但也失敗了
請幫助!
std::sort
期望您傳遞的比較器是某種可調用類型,無論是函數指針、函子還是 lambda 等。它只需要可以使用像bool compare(const T& left, const T& right)
這樣的簽名來調用的東西.
第一個問題是傳遞compFunc()
是調用函數compFunc
。 這應該會失敗,因為compFunc
需要兩個參數。 您應該傳遞函數本身,而不是它的返回值:
sort(data.begin(), data.end(), compFunc);
第二個問題是,在您的比較函數中,您應該通過引用來接受參數,而不是通過指針:
bool compFunc(const List_base& a, const List_base& b);
其中List_base
正是您要排序的元素類型。
第三個問題是compFunc
是一個非靜態成員函數。 這意味着該函數依賴於要使用的List_base
實例,並且您需要一個秘密的this
參數來調用它,如this->compFunc(...)
。 您應該改為將其設為static
或非成員,以便將其視為普通函數。
class List_base {
/* ... */
static bool compFunc(const List_base& a, const List_base& b);
};
bool List_base::compFunc(const List_base& a, const List_base& b){
return a.name < b.name;
}
此時您的排序應該有效。 如果您想在List_base::sortList
之外使用排序結果,您應該通過引用接受data
,以便調用者可以看到您所做的更改。 目前, sortList
按值接受列表,這意味着它始終會收到您傳遞給它的內容的副本。
也許最干凈的解決方法是使用“小於”運算符 ( <
),標准庫在許多情況下默認使用它來比較用戶定義的類型。 這可能類似於以下內容:
class List_base {
/* ... */
friend bool operator<(const List_base& a, const List_base& b){
return a.name < b.name;
}
};
有了這個,你不需要明確指定你自己的比較器,排序現在就像
sort(data.begin(), data.end());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.