C++中如何对二维vector数组各行从末尾开始的同位置元素分别求和
实现方案
核心思路
- 首先统计所有行的最大长度,确定需要计算的求和轮次
- 对每一个倒数位置(从倒数第1位到最长行的倒数第max_len位),遍历所有行,仅当行长度足够覆盖当前倒数位置时,取出对应元素累加即可
可运行代码示例
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<vector<int>> arr = {{1, 1}, {1, 3, 2}, {1, 6, 11, 6}}; vector<int> sumResult; int maxRowLen = 0; // 计算最长行的长度 for (const auto& row : arr) { maxRowLen = max(maxRowLen, static_cast<int>(row.size())); } // 按倒数位置依次求和 for (int k = 1; k <= maxRowLen; ++k) { int currentSum = 0; for (const auto& row : arr) { if (row.size() >= k) { currentSum += row[row.size() - k]; } } sumResult.push_back(currentSum); } // 输出验证结果 for (int val : sumResult) { cout << val << " "; } return 0; }
输出结果
运行后输出为 9 15 7 1,和需求的计算结果完全一致。
内容的提问来源于stack exchange,提问作者Diego Ramírez
相关产品推荐
相关产品推荐

