SuJit SuJit - 4 years ago 158
C++ Question

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 templates?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download