【问题标题】:Overload operator<< for finding sum of 2 D array重载运算符<<用于查找二维数组的总和
【发布时间】:2020-11-04 17:49:20
【问题描述】:

我正在用 C++ 做一些练习题。我遇到了一个问题,我想找到 2d 数组 的元素总和。我可以编写一个返回总和的 get sum 方法。但我正在探索是否可以重载“operator&lt;&lt;”方法以达到相同的结果。

#include <iostream>
using namespace std;

int operator<<(const int arr[5][5])
{
   int sum = 0;
   for (int i = 0; i < 5; i++)
   {
      for (int j = 0; j < 5; j++)
      {
         sum += arr[i][j];
      }
   }
   return sum;
}

int main()
{
   int arr[5][5] = { {1,2,3,4,5},
                    {2,3,4,5,6},
                    {3,4,5,6,7},
                    {4,5,6,7,8},
                    {5,6,7,8,9} };
   cout << &arr << endl;
}

我想像std::cout 方法一样获得总和。这可能吗?

【问题讨论】:

  • 我用这个词来形容你是“颠覆预期”。这是一件坏事。 operator&lt;&lt;() 预计会做两件事。你所提议的不是其中之一。这使您的代码更难理解。很多人对运算符的第二个含义还是很咸的,已经过了几十年了。
  • 当然你可以滥用“输出运算符”来打印总和。但这真的是您想要在这里实现的目标吗?
  • @sweenish 指的是Principle of least astonishment

标签: c++ arrays algorithm multidimensional-array operator-overloading


【解决方案1】:

您可以通过为operator&lt;&lt; 提供模板重载来获得所需的输出,该模板采用const&amp; int[row][col],如下所示。 这仅适用于int[row][col]

(See Live Online)

#include <iostream>
#include <numeric> // std::accumulate

template<std::size_t M, std::size_t N> 
std::ostream& operator<<(std::ostream& out, const int (&arr)[M][N]) /* noexcept */
{
    int sum = 0;
    for (std::size_t i = 0; i < M; ++i)
    {
#if false // either using `std::accumulate`        
        sum += std::accumulate(arr[i], arr[i] + N, 0);

#elif true // or using for- loop
        for (std::size_t j = 0; j < N; j++)
            sum += arr[i][j];
#endif
    }
    return out << sum;
}

旁注

【讨论】:

    【解决方案2】:

    使用std::accumulate,由于数组中的内存是线性的,所以可以使用数组的开始和结束作为迭代器。

    #include <iostream>
    #include <numeric>  
    
    int main()
    {
        int arr[5][5] = { {1,2,3,4,5},
                {2,3,4,5,6},
                {3,4,5,6,7},
                {4,5,6,7,8},
                {5,6,7,8,9} };
        int sum = 0;
        sum += std::accumulate(arr[0], arr[0]+sizeof(arr)/sizeof(arr[0][0]), 0);
        std::cout << "Sum of array arr[5][5]: " << sum << "\n";
    
    
    }
    

    【讨论】:

    • 不是 OP 要求的,而是他真正需要的。我喜欢。 ;-)
    猜你喜欢
    • 2016-03-31
    • 2013-03-16
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 2014-09-11
    • 1970-01-01
    相关资源
    最近更新 更多