Skip to content

Instantly share code, notes, and snippets.

@uekkie
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uekkie/362d9ab62d1ebf76f5b2 to your computer and use it in GitHub Desktop.
Save uekkie/362d9ab62d1ebf76f5b2 to your computer and use it in GitHub Desktop.
forループよりalgorithmがすき
#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; });
}
@uekkie
Copy link
Author

uekkie commented Jun 24, 2015

データ型の変更や、カウントアップさせる条件の変更がきても、algorithm+lambdaをつかったほうがこのみ。

あとで読んだときに、「処理ブロック」を認識するためのコストが低く、counterという一時的な変数で、可変なものが無くなるのがメリットに感じる

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment