【问题标题】:faster way to sort on value while retaining original index在保留原始索引的同时更快地对值进行排序
【发布时间】:2011-11-04 07:44:35
【问题描述】:

我希望能得到一些帮助,想出一种更快的方法来对值进行排序,同时保留原始订单的键。我宁愿避免使用 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;
}

【问题讨论】:

  • 也许我眼睛不好,但我没有看到matrix在分配后被设置,也没有看到column的声明位置可能它们的意思相同,你把它们弄混了?跨度>

标签: c++ c


【解决方案1】:

假设返回 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;
}

【讨论】:

  • 谢谢。我认为地图很慢,因为你不能预先分配
【解决方案2】:

首先,我看到您使用一维数组来模拟您的矩阵。第一步,我将创建一个带有索引的新数组:

int count = m*n;
int *indices = new int[count];
for (i=0;i<count;i++) indices[i] = i;

(我有一段时间没有用 C++ 编程了,所以我不知道你是否可以即时进行初始化)。

然后您可以更改排序方法以同时接受原始矩阵和新创建的索引数组并对其进行排序。

为了方便起见,我将转置矩阵以对行(连续索引)进行排序,而不是对列进行排序。

【讨论】:

    猜你喜欢
    • 2019-10-19
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    相关资源
    最近更新 更多