c++ - 二维数组之和
问题描述
如何比较二维数组中每一行的总和?
int arr[3][3];
2 2 3
5 8 9
4 1 2
我想将每一行的总和与这个二维数组的每一行进行比较,以检查是否存在任何两行具有相同的总和。
解决方案
正如评论中所建议的那样,您可能应该考虑使用std::array
或std::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
推荐阅读
- java - 无法初始化 Eureka servlet 上下文
- dns - 如何将特定的dns请求转发到bind9中的另一个dns服务器
- android - 使用 EncryptedSharedPreferences 时出现 ANR
- latex - 背页中的 12pt,Latex 对应于 Microsoft Word 中的字体 12?
- javascript - (节点:1984)UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“电子邮件”
- php - PHP日期函数不尊重 date_default_timezone_set
- wordpress - Nginx 反向代理:如何反向代理在外部 IP 上运行的 wordpress 站点
- git - 克隆一个镜像的本地 Git 存储库
- python - Python - 如何将过滤器应用于视频?
- python - 如何登录多个 Telegram 帐户并向群组发送消息