c++ - STL algorithms and iterators instead of "for" loops -
i guess there should someway write below piece of code without using "for" loops , using stl algorithms , iterators. if not wrong can guide me on how this?
std::vector<double> a(n); std::vector<double> b(n); std::vector<double> c(n); std::vector<double> d(n); for(int = 0; < n; ++i) a[i] = myfunction1(i); for(int = 0; < n; ++i) b[i] = myfunction2(a[i], i); for(int = 0; < n; ++i) c[i] = myfunction3(a[i], b[i]); for(int = 0; < n; ++i) d[i] = myfunction4(a[i], b[i], i);
typedef boost::counting_iterator<int> counter; std::transform(counter(0), counter(n), a.begin(), myfunction1); std::transform(a.begin(), a.end(), counter(0), b.begin(), myfunction2); std::transform(a.begin(), a.end(), b.begin(), c.begin(), myfunction3);
now write own version of std::transform
takes ternary function:
template <typename in1, typename in2, typename in3, typename out, typename func> out transform3(in1 first1, in1 last1, in2 first2, in3 first3, out out, func f) { while (first1 != last1) { *out++ = f(*first1++, *first2++, *first3++); } return out; } transform3(a.begin(), a.end(), b.begin(), counter(0), d.begin(), myfunction4);
i guess there might can variadic templates in c++0x transform_n
, if don't know is, i've never used them. not sure if can forward variable number of arguments modifications (in case wrapping * ++
around each one, were).
Comments
Post a Comment