您可以使用std::sort
对二元组列表{(24, 0), (55, 2), (22, 0), (1, 1)}进行排序。虽然不太美观,但我通常会这样做:
#include <vector>
#include <algorithm>
#include <utility>
typedef std::pair<double, int> Pair;
struct CmpPair
{
bool operator()(const Pair& a, const Pair& b)
{ return a.first < b.first; }
};
void sortingPermutation(
const std::vector<double>& values,
std::vector<int>& permutation)
{
std::vector<Pair> pairs;
for (int i = 0; i < (int)values.size(); i++)
pairs.push_back(Pair(values[i], i));
std::sort(pairs.begin(), pairs.end(), CmpPair());
typedef std::vector<Pair>::const_iterator I;
for (I p = pairs.begin(); p != pairs.end(); ++p)
permutation.push_back(p->second);
}
这里是测试:
#include <iostream>
int main()
{
std::vector<double> values;
values.push_back(24);
values.push_back(55);
values.push_back(22);
values.push_back(1);
std::vector<int> permutation;
sortingPermutation(values, permutation);
typedef std::vector<int>::const_iterator I;
for (I p = permutation.begin(); p != permutation.end(); ++p)
std::cout << *p << " ";
std::cout << "\n";
}