在保留原始索引的同时对值进行更快的排序
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
对象的数组,我不认为您的解决方案特别低效。也许您可以通过使用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++编程了,所以我不知道你是否可以在飞行中进行初始化)。
你可以改变一个排序方法来接受你的原始矩阵和新创建的索引数组,并对其进行排序。
为了使事情更容易,我将矩阵转置来排序行(连续索引),而不是列。
相关文章:
- 二叉排序树无法编译
- C++ 合并排序返回原始向量
- 如何在不通过插入排序更改原始矢量的情况下对 2D 矢量进行排序
- STL 排序,保留原始顺序
- 固定大小的容器,其中元素被排序,并可以为C 中的数据提供原始指针
- 如何在保留原始索引的同时对向量的向量进行排序
- 排序后如何将二维数组重置为原始形式
- 使用霍尔分区方案的快速排序算法返回原始未排序列表
- 使用来自 unique_ptr 向量的原始指针作为排序的 ID
- std::排序比较器,可以看到元素的(原始)索引
- 为什么我的选择排序返回原始向量中不在的值
- 如何从未排序的 std::vector 中删除重复项,同时使用算法保持原始排序
- C++快速排序向量并保留原始索引号
- 如何在不更改原始数组的情况下对指向结构的指针数组进行排序
- 对容器进行排序,然后在保留原始排序的情况下移动元素
- 对二维矢量进行排序,保持对原始索引的跟踪
- 对n维点进行排序,并跟踪原始索引
- 对数据结构进行排序并保存原始索引的记录
- 在保留原始索引的同时对值进行更快的排序
- 将拓扑排序列表与原始列表进行比较