Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding vectors of doubles of differing sizes in C++

Tags:

c++

vector

I have a number of vector containers of varying size each containing doubles. I would like to add the elements of each vector to create a single vector of doubles. This simple example will example what I'm talking about:

Consider two vectors A with three elements 3.0 2.0 1.0 and B with two elements 2.0 1.0. I would like to add both vectors starting at the last element and working backwards. This would give an array C with entries 3.0 4.0 2.0.

What would be the most elegant/efficent way of doing this?

Thanks!

like image 563
Wawel100 Avatar asked Nov 21 '25 17:11

Wawel100


1 Answers

Once you know you have one vector that is larger than the other

std::vector<double> new_vector = bigger_vector; // Copy the largest
std::transform(smaller_vector.rbegin(), smaller_vector.rend(), // iterate over the complete smaller vector 
    bigger_vector.rbegin(), // 2nd input is the corresponding entries of the larger vector  
    new_vector.rbegin(),    // Output is the new vector 
    std::plus<double>());   // Add em

This is nice because you don't have to do any loop indentation, and works on any sequence container that supports reverse iterators.

like image 78
no one important Avatar answered Nov 23 '25 05:11

no one important



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!