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?
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.
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.
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.
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> //...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With