2016-11-10 5 views
3

C++にはlambdasとstd :: bind1stがあり、std :: bind2ndとstd :: bindは非推奨です。std :: bind2ndとstd :: bind二次元配列と構造体の配列

しかし、C++の基礎から始めて、より良い新機能を理解することができます。

まず例:

だから、私はint型秒の配列を使用して、この非常に簡単なコードで始めのstd :: bind2nd

int array1[] = { 10, 20, 30, 40, 50, 60, 40 }; 
int c1, c2, c3; 

c1 = count_if(array1, array1 + 7, bind2nd(greater<int>(), 40)); 
c2 = count_if(array1, array1 + 7, bind2nd(less<int>(), 40)); 
c3 = count_if(array1, array1 + 7, bind2nd(equal_to<int>(), 40)); 
cout << "There are " << c1 << " elements that are greater than 40." << endl; 
cout << "There are " << c2 << " elements that are lesser than 40." << endl; 
cout << "There are " << c3 << " elements that are equal to 40." << endl; 

第二の例で:STDで::バインド

greater<int> big; 
less<int> small; 
equal_to<int> equal; 

c1 = count_if(array1, array1 + 7, bind(big, _1, 40)); 
c2 = count_if(array1, array1 + 7, bind(small, _1, 40)); 
c3 = count_if(array1, array1 + 7, bind(equal, _1, 40)); 
cout << "There are " << c1 << " elements that are greater than 40." << endl; 
cout << "There are " << c2 << " elements that are lesser than 40." << endl; 
cout << "There are " << c3 << " elements that are equal to 40." << endl; 

いずれの場合も

There are 2 elements that are greater than 40. 
There are 3 elements that are lesser than 40. 
There are 2 elements that are equal to 40. 

どのように私は以下のようなbidimentionalアレイと同じ操作を行うことができます:
(I座標第二と同じ操作を行わたい)

int array2[7][2] = { { 1, 10 }, { 2, 20 }, { 3, 30 }, 
        { 4, 40 }, { 5, 50 }, { 6, 60 }, { 4, 40 } }; 

のアレイと出力がありますよ

この場合、構造体の配列の 'int'フィールドと同じ操作を行いたいと思います。

誰でも手伝ってもらえますか?

はあなたに

+0

'std :: bind1st'、' std :: bind2nd'や 'std :: bind'を学ぶことは、新しい機能を理解するのに役立ちません。 – cpplearner

+0

@cpplearner、私はあなたに同意します。私はlambdaについて言及していますが、これは別の方法で実行することができますが、今日は、私が言及したデータ構造(std :: bind2ndとstd :: bind)を使用することに興味があります。それは私が今知りたいすべてです。 – user7140484

答えて

2

bind1stbind2ndに感謝し、彼らの兄弟は、C++ 11で非推奨となり、あからさまなC++ 17で削除されます。あなたがこれを知らなかった場合に備えて。 bind

が、解決策は非常に簡単です、あなたはbind式が構成可能であるという事実を利用することができますし、(簡潔にするため省略placeholders)データメンバ抽出するためにbindを使用することができます:bind2nd

auto gr = count_if(array3, array3 + 7, bind(greater<>{}, bind(&st::i, _1), 40)); 
auto ls = count_if(array3, array3 + 7, bind(less<>{}, bind(&st::i, _1), 40)); 
auto eq = count_if(array3, array3 + 7, bind(equal_to<>{}, bind(&st::i, _1), 40)); 

をそれは簡単ではない。いくつかのtypedefを持つ関数オブジェクト(関数を使うことはできません)を宣言する必要があります。そして、あなたがラムダを採用カムC++ 11では

auto old = count_if(array3, array3 + 7, bind2nd(my_greater{}, 40)); 

を呼び出すことができます

struct my_greater : binary_function<st, int, bool> 
{ 
    bool operator()(st const& l, int r) const { 
     return greater<>{}(l.i, r); 
    } 
}; 

:あなたはこれを容易にするためにbinary_functionを使用することができます

auto XI = count_if(array3, array3 + 7, [](st const& l){ return l.i > 40}); 

demo of all


もしあなたはC++ 11以降のものを入手できます。ほとんどの場合、lambdaを使う方が良い選択です。単に「良いデフォルト」だけではなく、より良い解決策になるためには、bindの状況を本当に歪めなければなりません。

+1

ありがとう、私の友人。間違いなくあなたは**素晴らしい** C++プログラマです。 – user7140484