[英]faster way to sort on value while retaining original index
I'm hoping to get some help coming up with a faster way to do a sort on value while retaining a key on the original order. 我希望能得到一些帮助,以更快的方式进行价值排序,同时保留原始订单上的关键。 I would prefer to avoid using boost and it does not need to be a stable sort. 我宁愿避免使用boost,它不必是稳定的排序。 This is the code I came up with, it works but is slow and inefficent. 这是我想出的代码,它可以运行,但是速度慢且效率低下。 I have no need to keep the map after the sort is complete. 排序完成后,我无需保留地图。
struct column_record
{
int index;
float value;
};
// sort each column on value while retaining index
column_record *preprocess_matrix(float *value, int m, int n)
{
std::multimap<float,int> column_map;
column_record *matrix = new column_record[m*n];
for (int i=0; i<n; i++)
{
for (int j=0; j<m; j++)
{
column_map.insert(std::pair<float,int>(value[m*i+j],j));
}
int j = 0;
for (std::multimap<float,int>::iterator it=column_map.begin(); it!=column_map.end(); it++)
{
matrix[m*i+j].index = (*it).second;
matrix[m*i+j].value = (*it).first;
j++;
}
column_map.clear();
}
return matrix;
}
Assuming it's fine to return the array of column_record
objects, I don't think your solution is particularly inefficient. 假设返回column_record
对象的数组column_record
,我认为您的解决方案效率不是column_record
。 You could make it cleaner perhaps and eliminate the need for std::multimap
by using STL algorithms: 您可以使用STL算法使它更整洁并消除对std::multimap
的需求:
bool compare_column_records(const column_record& lhs, const column_record& rhs)
{
return lhs.value < rhs.value;
}
column_record* preprocess_matrix(float* value, int m, int n)
{
const int num_elements = m * n;
column_record* matrix = new column_record[num_elements];
for (int i = 0; i < num_elements; ++i)
{
// not sure what you mean by index; it looks like you want column index only?
matrix[i].index = i;
matrix[i].value = value[i];
}
std::sort(matrix, matrix + num_elements, compare_column_records);
return matrix;
}
First, I see that you use a 1-dimensional array to emulate your matrix. 首先,我看到您使用一维数组来模拟矩阵。 First step, I'd create a new array with the indexes: 第一步,我将使用索引创建一个新数组:
int count = m*n;
int *indices = new int[count];
for (i=0;i<count;i++) indices[i] = i;
(I haven't programmed in C++ in a while so I don't know if you can do the initialisation on the fly). (我已经有一段时间没有用C ++编程了,所以我不知道您是否可以即时进行初始化)。
You could then alter a sort method to accept both your original matrix and the newly created indices array and sort on that. 然后,您可以更改排序方法以同时接受原始矩阵和新创建的索引数组,然后对其进行排序。
To make things easier, I'd transpose the matrix to sort the rows (consecutive indices), instead of columns. 为了使事情变得容易,我将对矩阵进行转置以对行(连续索引)而不是列进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.