2016-06-20 3 views
1

を比較する私は、次のタイプのベクトルがありますC++は機能

std::sort(neighbors.begin(), neighbors.end(), myFunc(index)); 

bool myFunc(const std::pair< std::pair< int, int >, float > &a, const std::pair< std::pair< int, int >, float > &b, const int index){ 
    return (a.second[index] > b.second[index]); 
} 
を次のように私は、並べ替え、次のベクトルを作成したいと思います

std::vector< std::pair< std::pair< int, int >, std::vector<float> > > neighbors; 

私は構文が間違っていることを知っていますが、ベクトルのその要素だけを比較するためのインデックスを提供したいと思います。

この引数をmyFuncに渡す方法がわかりません。

+0

サイドノート:std :: pairをより説明的なバージョン –

+0

で置き換えることができます。「その要素のみを比較しています...」とは何ですか?比較するには2つの要素が必要です。 – Octopus

答えて

0

ラムダ:

std::sort(
    neighbors.begin(), 
    neighbors.end(), 
    [index](const std::pair< std::pair< int, int >, std::vector<float> > &a, 
      const std::pair< std::pair< int, int >, std::vector<float> > &b) 
      { 
       return (a.second[index] > b.second[index]); 
      } 
); 

はdetailled導入のためWhat is a lambda expression in C++11?を参照してください。

+1

マイナーニック: 'std :: vector '、外側の 'std :: pair'の第2項目の' float'ではありません –

+0

@MarcoA。ありがとう。 (うーん、私はこの部分をコピーしたと確信していた...) – deviantfan

0

プリC++ 11解決策:カスタムコンパレータ

struct Comparator { 
    Comparator(int index) : index_(index) {} 
    bool operator() (const std::pair< std::pair< int, int >, std::vector<float> > &a, 
         const std::pair< std::pair< int, int >, std::vector<float> > &b) 
    { 
     return (a.second[index_] > b.second[index_]); 
    } 

    int index_; 
}; 

sort(neighbors.begin(), neighbors.end(), Comparator(42)); 

C++ 11 +ソリューションとして、オブジェクトのインスタンスを使用します。

std::sort(neighbors.begin(), neighbors.end(), [index] 
         (const std::pair< std::pair< int, int >, std::vector<float> > &a, 
          const std::pair< std::pair< int, int >, std::vector<float> > &b) 
    { 
    return (a.second[index] > b.second[index]); 
    } 
); 

私のアドバイスをラムダを使用します。のために行きますあなたがC++ 11の機能を使うことが許されているならば、ラムダ。それはもっとエレガントで読みやすいでしょう。