首页 > 解决方案 > 二维数组之和

问题描述

如何比较二维数组中每一行的总和?

int arr[3][3];
2 2 3
5 8 9
4 1 2

我想将每一行的总和与这个二维数组的每一行进行比较,以检查是否存在任何两行具有相同的总和。

标签: c++c++14

解决方案


正如评论中所建议的那样,您可能应该考虑使用std::arraystd::vector使某些事情变得更容易。

无论如何,您可以创建一个std::map总和作为Key和 astd::vector<size_t>作为Value来存储具有该总和的所有行。

#include <cstddef>
#include <iostream>
#include <iterator>
#include <map>
#include <numeric>
#include <vector>

template<typename T, size_t Y, size_t X>
auto sum_rows(const T (&arr)[Y][X]) {

    // "res" stores the sums mapped to row numbers
    std::map<T, std::vector<size_t>> res;

    // accumulate each row
    for(size_t y = 0; y < Y; ++y) {
        // the result of accumulate is the key in the map
        // the row is pushed back into the vector that is stored for that key
        res[std::accumulate(std::begin(arr[y]), std::end(arr[y]), T{})].push_back(y);
    }

    return res;
}

int main() {
    int arr[3][3]{
        {2, 2, 3},
        {5, 8, 9},
        {4, 1, 2}
    };

    auto res = sum_rows(arr);

    // show the result
    for(const std::pair<int, std::vector<size_t>>& sumrows : res) {
        int sum = sumrows.first;
        const std::vector<size_t>& rows = sumrows.second;

        std::cout << "rows with sum " << sum << " (" << rows.size() << "):";
        for(size_t row : rows) std::cout << ' ' << row;
        std::cout << '\n';
    }
}

输出:

rows with sum 7 (2): 0 2
rows with sum 22 (1): 1

推荐阅读