如何比较二维数组中每一行的总和?
int arr[3][3];
2 2 3
5 8 9
4 1 2
我想比较此二维数组的每一行与每一行的总和,以检查是否存在两行具有相同的总和。
std::array
或std::vector
,这会使某些事情变得容易得多。无论如何,有了现在的代码,您可以执行以下操作:
#include <algorithm>
#include <array>
#include <iostream>
#include <numeric>
#include <tuple>
#include <utility>
template<size_t Y, size_t X>
void func(int(&arr)[Y][X]) {
// an array to store sum and row number
std::pair<int, size_t> res[Y];
// accumulate each row
for(size_t y = 0; y < Y; ++y) {
res[y].first = std::accumulate(std::begin(arr[y]), std::end(arr[y]), 0);
res[y].second = y;
}
// sort the result
std::sort(std::begin(res), std::end(res));
// show the result - listed in ascending order of the sums
for(const auto& p : res) {
std::cout << "row: " << p.second << ' ' << "sum: " << p.first << '\n';
}
}
int main() {
int arr[3][3]{
{2, 2, 3},
{5, 8, 9},
{4, 1, 2}
};
func(arr);
}
输出
row: 0 sum: 7 row: 2 sum: 7 row: 1 sum: 22
因此,具有相同总和的所有行将在彼此之后列出。