c++ - Transform and accumulate with C++11 -


coming python wonder if c++ nowadays has functional things there in python.

currently trying figure out how produce sum of elements using indexes instead. example python would:

a = [ ... ] b = [ ... ]  sum(map(lambda i: a[i] * 2 - b[i + 1], range(len(a))) 

so here generate new array each element determined index arithmetic.

in stl there transform , accumulate, take iterators arguments. ok if on each step needed change concrete element. here need use index.

also transform have specify array need put results to. there way resulting array generated on fly , returned? python's map does.

because in such case it's easier write simple for-loop.

there's no need create intermediate array, leave std::transform out of picture. need std::accumulate sum intermediate result. but, you've noted, involves jumping through few hoops index given iterator.

int a[] = {10, 20, 30, 40}; int b[] = {1, 2, 3, 4, 5};  std::accumulate(std::begin(a), std::end(a), 0,                 [&](int acc, int& a_elem) {                     auto index = std::distance(a, &a_elem);                     return acc + a[index] * 2 - b[index + 1];                 }) 

live demo

this can cleaned quite bit if can use boost.range instead. allow generate range of integers can used indices, similar python example.

boost::accumulate(boost::irange<unsigned>(0, boost::size(a)), 0,                   [&](int acc, int index) {                     return acc + a[index] * 2 - b[index + 1];                   }) 

live demo


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -