elvis
elvis

Reputation: 1178

How to overload + operator for arrays in C++?

For a C++ exercise for school I need to overload the + operator to concatenate 2 arrays. And I need to do that in a generic class.

for ex:

a1 = {1, 3, 4}
a2 = {2, 3, 5, 6}
=> a = {1, 3, 4, 2, 3, 5, 6}

And I have this code but it's not working.

#include <iostream>
#include <array>

using namespace std;

template <class T>
T operator+(const T& a1, const T& a2)
{
  T a;
  for (typename T::size_type i = 0; i < a1.size() + a2.size; i++) {
      if (i < a1.size()) {
        a[i] = a1[i];
      } else {
          a[i] = a2[i];
      }
  }
  return a;
}

int main()
{
  array<int,3> a1 = { 1, 3, 4 };
  array<int,4> a2 = { 2, 3, 5, 6 };
  array<int,7> a3 = a1 + a2;

  for (int i = 0; i < 5; i++)
    cout << a1[i] << '+' << a2[i] << '=' << a3[i] << ' ';

  cout << endl;
  return 0;
}

This code doesn't work, this is what I receive in the console:

main.cpp:32:24: error: no match for ‘operator+’ (operand types are ‘std::array’ and ‘std::array’)
   array<int,7> a3 = a1 + a2;
                     ~~~^~~~
main.cpp:15:3: note: candidate: template T operator+(const T&, const T&)
 T operator+(const T& a1, const T& a2)

What should I do to resolve the problem? And another question, does this code use generic class? Any feedback will be appreciated!

Upvotes: 0

Views: 140

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122228

T operator+(const T& a1, const T& a2) takes two Ts as parameter and returns a T. That is not what you want.

This is how you can concatenate two arrays by using operator+:

#include <iostream>
#include <array>

    
template <typename T,size_t M,size_t N>
std::array<T,M+N> operator+(const std::array<T,M>& a1, const std::array<T,N>& a2) {
  std::array<T,M+N> a;
  for (size_t i = 0; i < M; ++i) {
      a[i] = a1[i];
  }
  for (size_t i = 0; i < N; ++i) {
      a[i + M] = a2[i];
  }
  return a;
}

int main() {
    std::array<int,3> a1 = { 1, 3, 4 };
    std::array<int,4> a2 = { 2, 3, 5, 6 };
    std::array<int,7> a3 = a1 + a2;

    for (const auto& e : a3){
        std::cout << e << " ";
    } 

    std::cout << "\n";
}

Your code somehow mixes elementwise addition and concatenation. And there were some typos in the implementation of operator+ (eg size instead of size() and accessing a2 out of bounds).

And another question, does this code use generic class?

No. Your operator+ (and the one above) is a free function. std::array is a generic container and std::array<int,N> is a class.

Upvotes: 2

Related Questions