Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Suppose I have two std::vectors x and y and a binary function F. I would like to create a new object z (not necessarily a vector), with the property that the ith elemenent of z will be the application of F to the ith elements of x and y. For the time being I use

boost::range::transform(x, y, z.begin(), F)

which of course requires memory allocation for z. My goal however is to avoid this memory allocation and have the transformation lazy evaluated, similarly to what boost::adaptors::transformed does with unary functions. In other words, the type of z would be some type of boost::range. Is there any easy way to do this or would I have to write my own range class? Thanks in advance!

share|improve this question
    
Is it easier to use and std::transform with back_inserter to make std::vector z and then make a range from it? –  maverik Jun 7 '13 at 11:07
    
@maverik: thanks for your answer. Unfortunately, that will not achieve my goal since memory would still need to be allocated for z (this time sequentially). –  linuxfever Jun 7 '13 at 11:26
    
Even if one could achieve lazy evaluation, how do you imagine avoiding memory allocation when the vector size is unknown at compile time? I can only think of reserving enough memory once instead of sequentially; and depending on the context, one could leverage alloca(). Are those two possibilities an option? –  klaus triendl Oct 30 '13 at 21:14

1 Answer 1

The problem is that Boost.Range does not provide a zip_range that can zip x and y as the inputfor your transform. So you need to write one yourself, e.g. using make_iterator_range and zip_iterator (from the Boost.Iterator library). See e.g. this answer for a code example.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.