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

I have two vectors with the same size

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 the forecasts in descending order using

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

Now I want to sort indexes along with predictions.

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

How can I do this without using boost and templates?

+4
source share
5 answers

You can combine these two vectors into one with the type of the type std::vector<std::pair<int, float>>and sort it. The comparison function may 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 as follows:

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

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

+6
source

@herohuyongtao , . . ,

struct MyPair
{
    float prediction;
    int index;
};

bool compare(MyPair &a, MyPair &b) { return a.prediction > b.prediction; }

vector<MyPair> std::sort compare.

, vector<MyPair> . vector<int>. !

+3

, :

    std::sort(indices.begin(), indices.end(),
          [&predictions](size_t i, size_t j)
          {return predictions[i] > predictions[j];});
    std::sort(predictions.begin(), predictions.end(),
          std::greater<float>());
+2

, , herohuyongtao, .

std::vector<std::pair<float, int>> predictions;
float * pixel = output.ptr<float>( 0 );
for ( int j = 0; j < output.cols; ++j ) {
    predictions.push_back({pixel[j], j});
}
std::sort(predictions.rbegin(), predictions.rend());
0

Sorting indices (provided that it is a number from 0 to N sequentially), for example:

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

using the comparison function, for example:

bool compareFunc(int &a, int &b)
{
    return predictions[a] > predictions[b];
}

This only sorts indexes, but forecasts can be accessed in sorted order using index values ​​from indexes!

Code:

#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

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

bool compareFunc(int &a, int &b) {
    return predictions[a] > predictions[b];
}

int main()
{
    std::sort(indices.begin(), indices.end(), compareFunc);
    for (auto i: indices) {
        cout << i << "\t" << predictions[i] << endl;
    }

    return 0;
}
0
source

Source: https://habr.com/ru/post/1624971/


All Articles