簡體   English   中英

使用以下命令對結構向量進行排序<algorithm>

[英]sorting a vector of structs using <algorithm>

我知道已經有關於它的問題了,我遵循了所有提示,但仍然無法解決問題,因此,我很樂意了解問題所在。

我有這個結構:

struct Scores
{
    int _score;
    std::string _name;
};

我想按_score對向量進行排序-從高到低。 這是我寫的:

std::sort (_scores.begin(), _scores.end(), myFunction);

我有這個功能:

bool myFunction (const struct Scores &i, const struct Scores &j)
    {return i._score>j._score;}

我已經包含了算法,所以我真的不知道出了什么問題。 我得到這些錯誤:

error C3867: 'HighScores::myFunction': function call missing argument list;
error C2780: 'void std::sort(_RanIt,_RanIt)' : expects 2 arguments - 3 provided

謝謝

您的示例中的myFunction似乎是成員類函數。 它必須是靜態的,然后才能成為std::sort算法的正確謂詞。 另外,您可以將此功能設為免費的出色功能。

或者你可以做一個函子

struct Sorter {
  bool operator ()( const Scores &o1, const Scores &o2) {
      return o1._score > o2._score;
  }
};

並將其實例傳遞給算法:

std::sort ( _scores.begin(), _scores.end(), Sorter());

除了@bits_international答案,您也可以像在C ++ 11中那樣

std::sort(_scores.begin(), _scores.end(), [](const Score& a, const Score& b) {
    return a._score > b._score;
});

希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM