Question

Any easy way to overload all kinds of arithmetic operators (+, -, *, /, +=, ...) for std::array and std::vector? The arithmetic operations are member-wise. Something like the following

template<class ContainerT, class opT>
ContainerT operator opT(ContainerT const& a, ContainerT const& b)
{
    ....
}

template<class ContainerT, class opT>
ContainerT operator opT=(ContainerT const& a, ContainerT const& b)
{
    ....
}
Was it helpful?

Solution

std::vector<int> input1(..);
std::vector<int> input2(..);
std::vector<int> output(input1.size());
std::transform (input1.begin(), input1.end(), input2.begin(), output.begin(), std::plus<int>());

There are other functors to choose from and you could always make your own or use a lambda.

OTHER TIPS

Do you want this?

#include <iostream>    // std::cout
#include <iterator>    // std::ostream_iterator, std::back_inserter
#include <algorithm>   // std::copy, std::transform
#include <vector>
#include <deque>
#include <list>

int main()
{
    std::vector<int> vt = { 1, 2, 3, 4, 5 };
    std::deque<int> de = { 3, 4, 5, 6, 7 };
    std::list<int> out;

    std::transform(vt.begin(), vt.end(), de.begin(), std::back_inserter(out),
        [](int a, int b) { return a + b; });

    std::copy(out.begin(), out.end(), std::ostream_iterator<int>(std::cout, "\n"));
}

Output is:

4
6
8
10
12

I think operator-overload to STL container, such as std::vector is not good. Instead, you can use std::valarray.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top