c++ - Make std::for_each more useful - is this a good idea for the functor to know the current index? -


often cannot use std::for_each because logic particular element depends on current index. end, i've invented functor class wraps main functor , passes current index. ideally want use lambda expressions. class have created safe , effective? there better solutions? did want wrapper's operator () return type of lambda expression, couldn't figure out. also, type should use index? should store main functor in wrapper value or reference?

thanks!

template<class func> class indexfunctor { public:     typedef func func_t;      explicit indexfunctor(const func_t& func) : func(func), index(0) {}      // how can return return type of func?     template<class t>     void operator ()(t& param)     {         func(index++, param);     }      const func_t& getfunctor() const     {         return func;     }      int getindex() const     {         return index;     }      void setindex(int index)     {         this->index = index;     }  private:     func_t func;     int index; };  template<class func> indexfunctor<func> with_index(const func& func) {     return indexfunctor<func>(func); }  void somefunc() {     std::vector<int> v(10);     std::for_each(v.begin(), v.end(), with_index([](int index, int x){ std::cout << "[" << index << "]=" << x << std::endl; })); } 

that should safe, although it's straightforward write indexed for-each yourself.

template <typename tinputiterator, typename tfunc> tfunc counted_for_each(tinputiterator first, tinputiterator last, tfunc func) {     (size_t = 0; first != last; ++first)     {         func(i++, *first);     }      return func; } 

less code , accomplishes same thing.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -