How to sort and rank a vector in C++ (without using C++11)

前端 未结 5 884
一个人的身影
一个人的身影 2021-01-21 19:07

I am trying to construct a function take takes a vector, ranks it, sorts it and outputs the sorted and ranked vector with the original positioning of the values. For example: I

5条回答
  •  遥遥无期
    2021-01-21 19:59

    Your problem is a misconception on rankings. Array indices are of size_t not float, so you'll need to return a vector not a vector.

    That said your sort is O(n2). If you're willing to use more memory we can get that time down to O(n log(n)):

    vector rankSort(const float* v_temp, const size_t size) {
        vector > v_sort(size);
    
        for (size_t i = 0U; i < size; ++i) {
            v_sort[i] = make_pair(v_temp[i], i);
        }
    
        sort(v_sort.begin(), v_sort.end());
    
        pair rank;
        vector result(size);
    
        for (size_t i = 0U; i < size; ++i) {
            if (v_sort[i].first != rank.first) {
                rank = make_pair(v_sort[i].first, i);
            }
            result[v_sort[i].second] = rank.second;
        }
        return result;
    }
    

    Live Example

    EDIT:

    Yeah this actually gets a little simpler when taking a vector instead of a float[]:

    vector rankSort(const vector& v_temp) {
        vector > v_sort(v_temp.size());
    
        for (size_t i = 0U; i < v_sort.size(); ++i) {
            v_sort[i] = make_pair(v_temp[i], i);
        }
    
        sort(v_sort.begin(), v_sort.end());
    
        pair rank;
        vector result(v_temp.size());
    
        for (size_t i = 0U; i < v_sort.size(); ++i) {
            if (v_sort[i].first != rank.first) {
                rank = make_pair(v_sort[i].first, i);
            }
            result[v_sort[i].second] = rank.second;
        }
        return result;
    }
    

    Live Example

提交回复
热议问题