LoginSignup
2
1

More than 5 years have passed since last update.

C++でもeach_with_indexがしたい

Posted at

ので作ってみた。車輪の再発明万歳。

enumerate.hpp
template<typename T1>
class enumerate : public std::unary_function<T1, void>{
    typedef unsigned long ul;
public:
    enumerate(std::function<void(T1, ul)> f) : index(0), func(f) {};
    enumerate(ul i, std::function<void(T1, ul)> f) : index(i), func(f) {};
    void operator()(T1 t1){
        func(t1, index);
        ++index;
    }
private:
    ul index;
    std::function<void(T1,  ul)> func;
};

使い方は以下の様に

sample.cpp
std::for_each(container.begin(), container.end(), enumerate<int>([&](int x, int i){
    // ...
}));

もっと色々したい場合はboost使う。

2
1
0

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
2
1