1

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)
{
    ....
}
user1899020
  • 13,167
  • 21
  • 79
  • 154
  • 1
    Well, I can tell you right now you're gonna have to overload all of them at least once. It should be possible to achieve with just one overloading per operator though. – j_random_hacker Mar 30 '14 at 04:34
  • You mean you want to perform an operator for each element? – Ben Mar 30 '14 at 04:34
  • 1
    Are the containers supposed to be digits? 1xN or Nx1 matrices? Regardless, it isn't going to get easier than writing *code* unless you use someone else's. – WhozCraig Mar 30 '14 at 04:37
  • 1
    it isn't clear what you want to do, do you want a map, a fold... just in place evaluation of a function... C++ gives you a lot of rope... does an array plus an int mean to add as an element or add each element? – Grady Player Mar 30 '14 at 04:38
  • 1
    This is what `std::valarray` is for. – chris Mar 30 '14 at 04:50
  • 1
    You can't make the operator a template parameter, but you can use "preprocessor" macros to make each of the operators a one-liner. For all the evils of macros, that's very safe if you use the form `#ifdef X` / `#error Macro X already defined` / ... / `#undef X`. – Tony Delroy Mar 30 '14 at 05:28

2 Answers2

5
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.

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91
2

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.

ikh
  • 10,119
  • 1
  • 31
  • 70