直升机,
我想知道这是否有任何工作方法? 我正在努力使这项工作,但没有运气。
int mat[3][3];
mat[0][0] = 4;mat[0][1] = 5;mat[0][2] = 3;
mat[1][0] = 3;mat[1][1] = 2;mat[1][2] = 1;
mat[2][0] = 1;mat[2][1] = 8;mat[2][2] = 9;
有什么想法吗? :)
答案 0 :(得分:5)
更加惯用的C ++方法(与原始的数组数组相比)将是一个向量矢量,即。 std::vector<std::vector<int> >
然后在顶层向量上调用std::sort
。您可以传递sort
自定义谓词,根据平均值对两行进行比较。
答案 1 :(得分:3)
您应该创建一个由元组数组组成的临时数据结构。元组将是行索引和该行索引的平均值。然后使用标准sort()函数根据平均值对此元组数组进行排序。然后,运行已排序的元组数组以重新计算已排序的矩阵。
这将为您提供在排序例程完成交换期间不复制矩阵行的性能优势。如果你的行中只有3个元素,那么交换整行可能没问题。但随着您增加列数,交换将成为瓶颈。
在“伪代码”中,您可以执行以下操作:
function sort(input, numrows, numcols)
{
pair<int, int> index[numrows];
for (int i=0 to numrows) {
index[i].second = i;
// compute average of row[i] in the input matrix
index[i].first = average_of_row(&input[i]);
}
// STL sort will sort the pair based on the average (.first member)
sort(index.begin(), index.end());
for (int i=0 to index.size())
{
// copy rows from input matrix to output matrix
copy_row(&input[index[i].second], &output_matrix[i]);
}
return output;
}
答案 2 :(得分:1)
按照@Peter的建议,
#include <algorithm>
#include <numeric>
#include <vector>
using namespace std;
bool comp(vector<int> a, vector<int> b) {
if (a.size() == 0 || b.size() == 0) return false;
int sum_a = accumulate(a.begin(), a.end(), 0);
int sum_b = accumulate(b.begin(), b.end(), 0);
return sum_a / (double)a.size() < sum_b / (double)b.size();
}
int main() {
vector<vector<int> > mat(3, vector<int>(3));
mat[0][0] = 4; mat[0][1] = 5; mat[0][2] = 3;
mat[1][0] = 3; mat[1][1] = 2; mat[1][2] = 1;
mat[2][0] = 1; mat[2][1] = 8; mat[2][2] = 9;
sort(mat.begin(), mat.end(), comp);
return 0;
}
我不确定处理空向量的最佳方法,所以我只是让它返回false。当然,你可以给comp()
一个更有意义的名字。
编辑:我认为处理零大小矢量的更好方法是繁殖,
bool comp(vector<int> a, vector<int> b) {
int sum_a = accumulate(a.begin(), a.end(), 0);
int sum_b = accumulate(b.begin(), b.end(), 0);
return sum_a * b.size() < sum_b * a.size();
}
答案 3 :(得分:0)
将行放在多个集合中并重载&lt;运营商。这是一个例子: