Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort two vectors simultaneously in c++ without using boost or creating templates?

I have two vectors with same sizes

vector<float> predictions;      //say {1.22, 3.22, 2.22, 4.22}
vector<int> indices;            //say {0, 1, 2, 3}

I sorted the values in predictions in descending order using

std::sort(predictions.rbegin(), predictions.rend());     //gives {4.22, 3.22, 2.22, 1.22}

Now I want to sort indices simultaneously with the predictions.

//to get {3, 1, 2, 0}

How do I do it without using boost and custom templates?

like image 675
Sujit Avatar asked Jan 19 '16 13:01

Sujit


People also ask

How do you sort two vectors simultaneously?

For example to sort two vectors i would use descending bubble sort method and vector pairs. For descending bubble sort, i would create a function that requires a vector pair. After that i would put your 2 vector values into one vector pair.

How do I sort custom vectors?

You can sort a vector of custom objects using the C++ STL function std::sort. The sort function has an overloaded form that takes as arguments first, last, comparator. The first and last are iterators to first and last elements of the container.

How do you sort the elements of a vector?

A vector in C++ can be easily sorted in ascending order using the sort() function defined in the algorithm header file. The sort() function sorts a given data structure and does not return anything. The sorting takes place between the two passed iterators or positions.

How do you store a sorted vector in another vector?

One way you could do this would be to store the Names and Scores in a single data structure such as a std::vector<std::pair<std::string,int>> and then sorting can be done as follows: #include <algorithm> #include <vector> #include <string> #include <utility> //...


1 Answers

You can combine these two vectors into one with type like std::vector<std::pair<int, float>> and sort it instead. The compare function can be like this:

bool compareFunc(std::pair<int, float> &a, std::pair<int, float> &b)
{
    return a.second > b.second;
}

And sort the combined data like this:

std::sort(data.begin(), data.end(), compareFunc);

After this, you can get the sorted parts, i.e. its first component.

like image 115
herohuyongtao Avatar answered Nov 15 '22 06:11

herohuyongtao