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

前端 未结 5 945
一个人的身影
一个人的身影 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:48

    v_sort[i] is a float (it's just an element of v_sort vector) while only integral types can be used as array subscripts.

    Probably you meant v_sort as an array of indices, thus, you should declare it as std::vector or std::vector something like that.

    UP: Also, given that you change the values of the array passed, it's not an elegant way of pass it by const reference.

    To sum up, the following code compiles correctly on my machine:

    std::vector rankSort(float *v_temp, size_t size)
    {
        vector  v_sort;
        //create a new array with increasing values from 0 to n-1
        for(unsigned i = 0; i < size; i++)
        {
            v_sort.push_back(i);
        }
        bool swapped = false;
        do
        {
            for(unsigned i = 0; i < size; i++)
            {
                if(v_temp[v_sort[i]] > v_temp[v_sort[i+1]]) //error line
                {
                    unsigned temp = v_sort[i];
                    v_sort[i] = v_sort[i+1];
                    v_sort[i+1] = temp;
                    swapped = true;
                }
            }
        }
        while(swapped);
        return v_sort;
    }
    
    std::vector rankSort(std::vector &v_temp)
    {
        return rankSort(&v_temp[0], v_temp.size());
    }
    

提交回复
热议问题