How to add two vectors element‑wise in C++

1 Answer

0 votes
// How do you add two vectors element‑wise? Use std::transform with std::plus<>.

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

std::vector<double> add(const std::vector<double>& a,
                        const std::vector<double>& b) {
    std::vector<double> out(a.size());
    std::transform(a.begin(), a.end(), b.begin(), out.begin(), std::plus<>());
    return out;
}

int main() {
    std::vector<double> a = {1, 2, 3};
    std::vector<double> b = {4, 5, 6};

    auto c = add(a, b);
    std::cout << "Sum: [" << c[0] << ", " << c[1] << ", " << c[2] << "]\n";
}


/*
run:

Sum: [5, 7, 9]

*/

 



answered 3 hours ago by avibootz

Related questions

2 answers 161 views
2 answers 167 views
2 answers 132 views
2 answers 147 views
1 answer 167 views
1 answer 215 views
215 views asked Jul 3, 2021 by avibootz
...