C++中如何按指定列值对矩阵(嵌套数组)的行进行排序
按指定列排序嵌套数组(世界杯小组赛积分排序)
问题描述
开发世界杯小组赛结果控制台应用时,需根据各队积分(每行最后一个元素)对存储球队统计数据的嵌套数组行进行排序,生成符合要求的输出数组。
输入数组
inputArray[4][7] { {0, 2, 1, 1, 3, -2, 2}, {1, 1, 1, 3, 3, 0, 4}, {2, 0, 1, 3, 1, 2, 6}, {1, 1, 1, 2, 2, 0, 4}, }
期望输出数组
outputArray[4][7] { {2, 0, 1, 3, 1, 2, 6}, {1, 1, 1, 3, 3, 0, 4}, {1, 1, 1, 2, 2, 0, 4}, {0, 2, 1, 1, 3, -2, 2}, }
解决方案
核心逻辑:以每行最后一个元素为排序依据降序排列;积分相同时保持原数组中的相对顺序(稳定排序)。
Python 实现
def sort_teams_by_points(input_array): # 按每行最后一个元素降序排序,sorted默认是稳定排序 return sorted(input_array, key=lambda x: x[-1], reverse=True) # 测试输入 input_array = [ [0, 2, 1, 1, 3, -2, 2], [1, 1, 1, 3, 3, 0, 4], [2, 0, 1, 3, 1, 2, 6], [1, 1, 1, 2, 2, 0, 4] ] output_array = sort_teams_by_points(input_array) for row in output_array: print(row)
JavaScript 实现
function sortTeamsByPoints(inputArray) { // 复制数组避免修改原数据,sort方法为ES2019+稳定排序 return [...inputArray].sort((a, b) => b[b.length - 1] - a[a.length - 1]); } // 测试输入 const inputArray = [ [0, 2, 1, 1, 3, -2, 2], [1, 1, 1, 3, 3, 0, 4], [2, 0, 1, 3, 1, 2, 6], [1, 1, 1, 2, 2, 0, 4] ]; const outputArray = sortTeamsByPoints(inputArray); outputArray.forEach(row => console.log(row));
C++ 实现
#include <iostream> #include <vector> #include <algorithm> using namespace std; // 自定义排序规则:按每行最后一个元素降序 bool compareTeams(const vector<int>& a, const vector<int>& b) { return a.back() > b.back(); } vector<vector<int>> sortTeamsByPoints(vector<vector<int>> inputArray) { sort(inputArray.begin(), inputArray.end(), compareTeams); return inputArray; } int main() { vector<vector<int>> inputArray = { {0, 2, 1, 1, 3, -2, 2}, {1, 1, 1, 3, 3, 0, 4}, {2, 0, 1, 3, 1, 2, 6}, {1, 1, 1, 2, 2, 0, 4} }; vector<vector<int>> outputArray = sortTeamsByPoints(inputArray); for (const auto& row : outputArray) { for (int num : row) { cout << num << " "; } cout << endl; } return 0; }
内容的提问来源于stack exchange,提问作者EduMurbol
相关产品推荐
相关产品推荐

