Element-wise max between two arrays

Hi guys. I think my question is pretty simple.

What is the best way of making element-wise max operation on two std::array s in c++?

Example:

array1 = {4,5,3,2,1,7}
array2 = {3,4,2,6,7,1}
array3 = max(array1,array2);
then
array3 = {4,5,3,6,7,7}

Thanks,

Dario
Make a function that accepts 3 arrays.

1
2
3
4
5
6
7
for every i from 0 to SIZE 
     if array1[i]  > array2[i]
            // do something
     else if array1[i]  < array2[i]
            // do something
     else // do something
end for-loop


Translate pseudo-code to c++ and fill in the missing pieces.
Last edited on
1
2
std::transform (array1, array1 + size, array2,
                std::back_inserter(result), std::greater<int> {});
Last edited on
Great mbozzi!!!

This is what I was looking for:

This is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// array::fill example
#include <iostream>
#include <array>
#include <valarray>

int main () {
  std::array<int,6> array1 = {4,5,3,2,1,7}, array2 = {3,4,2,6,7,7};
  std::vector<int> result;


  std::cout << "array1 contains:";
  for ( int& x : array1) { std::cout << ' ' << x; }

  std::cout << '\n';

  std::cout << "array2 contains:";
  for ( int& x : array2) { std::cout << ' ' << x; }

  std::cout << '\n';

  std::transform (array1.begin(), array1.end(), array2.begin(), std::back_inserter(result), [](int a, int b) {return std::max(a,b);});

  std::cout << "result contains:";
  for ( int& x : result) { std::cout << ' ' << x; }

  std::cout << '\n';

  return 0;
}


This is the output

array1 contains: 4 5 3 2 1 7
array2 contains: 3 4 2 6 7 7
result contains: 4 5 3 6 7 7


Thanks a lot
Topic archived. No new replies allowed.