C++ c++;基于平均行值的二维数组行排序
你好 我想知道有没有什么工作方法? 我试着让这一切顺利,但运气不好C++ c++;基于平均行值的二维数组行排序,c++,arrays,C++,Arrays,你好 我想知道有没有什么工作方法? 我试着让这一切顺利,但运气不好 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; 有什么想法吗?:) > P>一种更为习惯化的C++方式(与数组的原始方法相对应)有向量向量,即:代码> STD:
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;
有什么想法吗?:) > P>一种更为习惯化的C++方式(与数组的原始方法相对应)有向量向量,即:代码> STD::vector < /Cord>,然后调用顶级代码中的“代码> STD::排序< /COD>”。您可以传递一个自定义谓词,该谓词根据两行的平均值对两行进行比较。您应该创建一个临时数据结构,即元组数组。元组将是行索引和该行索引的平均值。然后使用标准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;
}
函数排序(输入、numrows、numcols)
{
配对指数[numrows];
对于(int i=0到numrows){
索引[i],秒=i;
//计算输入矩阵中第[i]行的平均值
索引[i]。第一个=行的平均值(&输入[i]);
}
//STL sort将根据平均值(.first member)对该对进行排序
排序(index.begin(),index.end());
for(对于index.size(),int i=0)
{
//将行从输入矩阵复制到输出矩阵
复制_行(&input[index[i].second],&output_矩阵[i]);
}
返回输出;
}
按照@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;
}
将行放入多集中,并重载<运算符。下面是一个1D示例:
请注意,不需要计算平均值,只需计算总和(所有行的列数相同)。这可以通过
索引[i]完成。first=accumulate(输入[i],输入[i]+numcols)
。另外,copy_row应该是std::copy(输入[index[i].second],输入[index[i].second],输出矩阵[i])
应该因为我懒得自己写代码而得到一次投票:)
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();
}