LoginSignup
6
6

More than 5 years have passed since last update.

STL for_each省略形

Last updated at Posted at 2013-06-14

コンテナとラムダ式ぶち込むだけでいいのさ。

#include    <algorithm>

    template<typename CONTAINER,typename FUNCTION>
    static FUNCTION ForEach(const CONTAINER& container,FUNCTION function){
        return std::for_each(container.begin(),container.end(),function);
    }

使用例


#include <iostream>
#include <vector>
#include <random>

#include    <algorithm>

    template<typename CONTAINER,typename FUNCTION>
    static FUNCTION ForEach(const CONTAINER& container,FUNCTION function){
        return std::for_each(container.begin(),container.end(),function);
    }

int main(int argc,char* argv[]){

    std::vector<int> cont;
    std::mt19937 engine;
    std::uniform_int_distribution<int> distribution(1,100);
    for(int i = 0;i < 10;i++)
        cont.push_back(distribution(engine));

    ForEach(cont,[&](int i){std::cout << i<<"\t";});

    return 0;

}

2013/06/17追記
もし、boost::for_eachと同じ処理をしたいのであれば

    FUNCTION ForEach(const CONTAINER& container,FUNCTION function)

    FUNCTION ForEach( CONTAINER& container,FUNCTION function)

というようにconstはずせば通ります。
全体はこんな感じ

#include    <algorithm>

    template<typename CONTAINER,typename FUNCTION>
    static FUNCTION ForEach(CONTAINER& container,FUNCTION function){
        return std::for_each(container.begin(),container.end(),function);
    }

6
6
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6