在保留原始索引的同时对值进行排序的更快方法

时间:2011-08-26 07:57:10

标签: c++ c

我希望得到一些帮助,以更快的方式对价值进行排序,同时保留原始订单上的密钥。我宁愿避免使用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;
}

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

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

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

(我之前没有用C ++编程,所以我不知道你是否可以动态进行初始化。)

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

为了简化操作,我会调整矩阵来对行(连续索引)进行排序,而不是列。

相关问题