[英]faster way to sort on value while retaining original index
我希望能得到一些幫助,以更快的方式進行價值排序,同時保留原始訂單上的關鍵。 我寧願避免使用boost,它不必是穩定的排序。 這是我想出的代碼,它可以運行,但是速度慢且效率低下。 排序完成后,我無需保留地圖。
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;
}
假設返回column_record
對象的數組column_record
,我認為您的解決方案效率不是column_record
。 您可以使用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;
}
首先,我看到您使用一維數組來模擬矩陣。 第一步,我將使用索引創建一個新數組:
int count = m*n;
int *indices = new int[count];
for (i=0;i<count;i++) indices[i] = i;
(我已經有一段時間沒有用C ++編程了,所以我不知道您是否可以即時進行初始化)。
然后,您可以更改排序方法以同時接受原始矩陣和新創建的索引數組,然后對其進行排序。
為了使事情變得容易,我將對矩陣進行轉置以對行(連續索引)而不是列進行排序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.