Adding doubling vectors of different sizes in C ++

I have several vector containers of different sizes, each of which contains paired. I would like to add elements of each vector to create one twin vector. This simple example will be an example of 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 from the last element and working in the opposite direction. This will give a C array with records 3.0 4.0 2.0.

What would be the most elegant / efficient way to do this?

Thank!

+3
source share
3 answers

Once you know that you have one vector that is bigger 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

, - , .

+3

:

#include <vector>

void add(
        std::vector<double>& result,
        const std::vector<double>& a,
        const std::vector<double>& b)
{
    std::vector<double>::const_reverse_iterator sit;
    std::vector<double>::const_reverse_iterator send;

    // copy the larger vector
    if (a.size() > b.size() ) {
        result = a;
        sit  = b.rbegin();
        send = b.rend();
    }
    else {
        result = b;
        sit  = a.rbegin();
        send = a.rend();
    }

    // add the smaller one, starting from the back
    for (std::vector<double>::reverse_iterator it = result.rbegin();
            sit != send;
            ++it, ++sit)
    {
        *it += *sit;
    }
}
+4

C, (+ =) C.

Somthing like:

std::vector<double> add(const std::vector<double>& a,
                        const std::vector<double>& b)
{
    std::vector<double> c( (a.size() > b.size()) ? a : b );
    const std::vector<double>& aux = (a.size() > b.size() ? b : a);
    size_t diff = c.size() - aux.size();

    for (size_t i = diff; i < c.size(); ++i)
        c[i] += aux[i-diff];

    return c;
}

, , [] .

, - , , - :

std::vector<double> add(const std::vector<double>& a, 
                        const std::vector<double>& b)
{
    std::vector<double> c( (a.size() > b.size()) ? a : b);
    std::vector<double>::reverse_iterator c_i;

    const std::vector<double>& aux = (a.size() > b.size()) ? b : a;
    std::vector<double>::const_reverse_iterator aux_i;

    for (c_i=c.rbegin(), aux_i=aux.rbegin(); aux_i!=aux.rend(); ++c_i, ++aux_i)
        *c_i += *aux_i;

    return c;
}

, , .

+3

Source: https://habr.com/ru/post/1762481/


All Articles