• Source
    1. // Example program
    2. #include <iostream>
    3. #include <string>
    4. #include <vector>
    5. #include <algorithm>
    6. #include <functional>
    7. #include <cassert>
    8. #include <iomanip>
    9. #include <numeric>
    10.  
    11. template <typename T, typename Compare>
    12. void getSortPermutation(
    13. std::vector<unsigned>& out,
    14. const std::vector<T>& v,
    15. Compare compare = std::less<T>())
    16. {
    17. out.resize(v.size());
    18. std::iota(out.begin(), out.end(), 0);
    19.  
    20. std::sort(out.begin(), out.end(),
    21. [&](unsigned i, unsigned j){ return compare(v[i], v[j]); });
    22. }
    23.  
    24. template <typename T>
    25. void applyPermutation(
    26. const std::vector<unsigned>& order,
    27. std::vector<T>& t)
    28. {
    29. assert(order.size() == t.size());
    30. std::vector<T> st(t.size());
    31. for(unsigned i=0; i<t.size(); i++)
    32. {
    33. st[i] = t[order[i]];
    34. }
    35. t = st;
    36. }
    37.  
    38. template <typename T, typename... S>
    39. void applyPermutation(
    40. const std::vector<unsigned>& order,
    41. std::vector<T>& t,
    42. std::vector<S>&... s)
    43. {
    44. applyPermutation(order, t);
    45. applyPermutation(order, s...);
    46. }
    47.  
    48. // sort multiple vectors using the criteria of the first one
    49. template<typename T, typename Compare, typename... SS>
    50. void sortVectors(
    51. const std::vector<T>& t,
    52. Compare comp,
    53. std::vector<SS>&... ss)
    54. {
    55. std::vector<unsigned> order;
    56. getSortPermutation(order, t, comp);
    57. applyPermutation(order, ss...);
    58. }
    59.  
    60. // make less verbose for the usual ascending order
    61. template<typename T, typename... SS>
    62. void sortVectorsAscending(
    63. const std::vector<T>& t,
    64. std::vector<SS>&... ss)
    65. {
    66. sortVectors(t, std::less<T>(), ss...);
    67. }
    68.  
    69. using namespace std;
    70.  
    71. int main()
    72. {
    73. vector<int> id = {1, 0, 2, 3};
    74. vector<string> name = {"Tuket", "Rufol", "Muscul", "Jigoro"};
    75. vector<string> surname = {"Troco", "Conino", "Man", "Kano"};
    76. vector<unsigned> age = {24, 11, 20, 78};
    77.  
    78. sortVectors(surname, greater<string>(), id, name, surname, age);
    79.  
    80. for(int i=0; i<4; i++)
    81. {
    82. cout
    83. << setw(3) << id[i] << " "
    84. << setw(10) << name[i] << " "
    85. << setw(10) << surname[i] << " "
    86. << setw(3) << age[i] << endl;
    87. }
    88. }
    89.