Last active
August 29, 2015 14:23
-
-
Save uekkie/362d9ab62d1ebf76f5b2 to your computer and use it in GitHub Desktop.
forループよりalgorithmがすき
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <algorithm> | |
//※ 下のサンプルコードは概念。ノーテストなので動作保証なし。 | |
// たくさんの整数値が入ってる前提 | |
std::vector<int> repository; | |
// N の出現回数のカウント(for版) | |
// for版のポイント | |
// ・一時変数 count が | |
int CountN(int N) | |
{ | |
int counter = 0; | |
for each( int val in repository) | |
{ | |
val == N ? ++counter : continue; | |
} | |
return counter; | |
} | |
// N の出現回数のカウント(algorithm版) | |
int CountN(int N) | |
{ | |
return std::count(repository.begin(), repository.end(), N ); | |
} | |
// repository のデータ構造が int → Humanに変化したら、、、 | |
// | |
struct Human | |
{ | |
int age; | |
std::string name; | |
}; | |
// N の出現回数のカウント(for版) | |
// for版のポイント | |
// ・一時変数 count が | |
int CountN(int N) | |
{ | |
int counter = 0; | |
for each( Human val in repository) | |
{ | |
val.age == N ? ++counter : continue; | |
} | |
return counter; | |
} | |
// N の出現回数のカウント(algorithm版) | |
int CountN(int N) | |
{ | |
return std::count_if(repository.begin(), repository.end(), [](Human val){ return val.age == N; }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
データ型の変更や、カウントアップさせる条件の変更がきても、algorithm+lambdaをつかったほうがこのみ。
あとで読んだときに、「処理ブロック」を認識するためのコストが低く、counterという一時的な変数で、可変なものが無くなるのがメリットに感じる