2017-09-13 10 views
0

hereの解を辿って、ペアのベクトルをソートしました。ペアのソートベクトル:一致する関数がありません

そして、私はコードで

linear_problem.h:275: 

error: no matching function for call to 

‘sort(std::vector<std::pair<int, double> >::iterator, 
std::vector<std::pair<int, double> >::iterator, <unresolved overloaded 
function type>)’ 
    std::sort(data.begin(), data.end(), compareFunc); 

クラスを取得するには、次のとおりです。

class Coefficients{ 
private: 
    std::vector<std::pair<int, double>> data; 

public: 
    Coefficients(){} 
    bool compareFunc(const std::pair<int, double> &a, const std::pair<int, double> &b){ 
     return a.first > b.first; 
    } 

    void sort(){ 
     std::sort(data.begin(), data.end(), compareFunc); 
    } 

}; 

コードはかなりの例のようなものですので、私は間違っている可能性が何の見当がつかない。

+3

「compareFunc」は、「係数」のメンバー関数です。 'std :: sort'が持たない' Coefficients'型のオブジェクトでのみ呼び出すことができます。比較関数を 'Coefficients'の外に置くか、' static'にするのですか? – nwp

答えて

4

compareFunc()はメンバ関数であり、呼び出すにはCoefficientsのインスタンスが必要です。

あなたはその問題を解決するために、それstaticクラスのメンバ関数にすることができます。

static bool compareFunc(const std::pair<int, double> &a, const std::pair<int, double> &b){ 
// ^^^^^^ 
     return a.first > b.first; 
    } 

    void sort(){ 
     std::sort(data.begin(), data.end(), &Coefficients::compareFunc); 
             // ^^^^^^^^^^^^^^ 
    } 
+0

優れています。私はC++でこれほど多くの経験がないので、何が起こっているのか分かりませんでした。 –

2

C++ 14を使用して、最善の解決策は、ラムダ

std::sort(v.begin(), v.end(), [](auto &left, auto &right) { 
    return left.second < right.second; 
}); 

かのおかげで書くのは非常に簡単です

struct comp{ 
    bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) { 
     return left.second < right.second; 
    } 
}; 

std::sort(v.begin(), v.end(), comp()); 
関連する問題