Home > front end >  How do I get weighted sum of 2 vectors in C ?
How do I get weighted sum of 2 vectors in C ?

Time:11-14

I saw the post here to sum 2 vectors. I wanted to do a weighted sum.

std::vector<int> a;//looks like this: 2,0,1,5,0
std::vector<int> b;//looks like this: 0,0,1,3,5

I want to do a * 0.25 b * 0.75 and store in some vector. I saw this function std::transform but wanted to know how do I write a custom operation for that.

CodePudding user response:

Version 1: Using std::transform and a lambda

#include <iostream>
#include <vector>
#include<algorithm>

int main()
{ 
    std::vector<int> a{2,0,1,5,0};
    std::vector<int> b{0,0,1,3,5};

    //create a new vector that will contain the resulting values
    std::vector<double> result(a.size());
    std::transform (a.begin(), a.end(), b.begin(), result.begin(), [](int p, int q) -> double { return (p * 0.25)   (q * 0.75); });
    for(double elem: result)
    {
        std::cout<<elem<<std::endl;
    }
    return 0;
}

Version 2: Using a free function

#include <iostream>
#include <vector>
#include<algorithm>
double weightedSum(int p, int q)
{
    return (p * 0.25)   (q * 0.75);
}
int main()
{ 
    std::vector<int> a{2,0,1,5,0};
    std::vector<int> b{0,0,1,3,5};

    //create a new vector that will contain the resulting values
    std::vector<double> result(a.size());
    std::transform (a.begin(), a.end(), b.begin(), result.begin(), weightedSum);
    for(double elem: result)
    {
        std::cout<<elem<<std::endl;
    }
    return 0;
}
  • Related