2014-02-27 49 views
-1

您好我想排序向量的成員。我見過類似的問題,但所面臨的錯誤是不同的。我跟隨在cplusplus.com排序結構中的成員的向量C++

struct Food { 
    char[8] Name; 
    float Price; 
} 

的 「排序」 的步驟,我有一個載體

std::vector<Food> FoodList; 

而且我有一個比較功能:

bool comparePrice (Food f1, Food f2) { return (f1.Price<f2.Price); } 

而且最後我的排序聲明:

std::sort(FoodList.begin(),FoodList.end(),comparePrice); 

但我是前遇到錯誤,該排序需要2個參數,但我給了3.但是,當我在MVS2010中編寫程序時,它會提示我輸入3個參數。有人可以幫忙嗎?

+0

在發佈有關錯誤的問題,請提供準確,完整的錯誤。請編輯您的問題以包含它。 –

+0

我很驚訝,你得到有關(有效的)'std :: sort'調用的錯誤,但不是其非法字段定義的結構定義? –

+0

char [8]名稱應該是char名稱[8] .. –

回答

2

有幾個問題與您的代碼,請參見下面的註釋:

struct Food { 
    char[8] Name; // this should be: char Name[8];, and even better std::string 
    float Price; 
} // missing semicolon here ; 

// You should use const Food& as parameter type 
bool comparePrice (Food f1, Food f2) { return (f1.Price<f2.Price); } 
+0

但根據http://en.cppreference.com/w/cpp/algorithm/sort你不必使用常量引用作爲函數參數。 – nndru

+0

你有:'比較函數的簽名應該等同於以下內容: bool cmp(const Type1&a,const Type2 &b);'。在我的VS2005編譯器中,甚至用'(Food f1,Food f2)'編譯。使用'const T&'實際上是一種很好的做法,你不會按值複製(多數民衆贊成有效),並且const說你的函數不會改變參數。 – marcinj