Chapter 37. Sorting by indexes

#include <x/algorithm.H>

std::vector<size_t> order_by={6,3,5,4,2,0,1,7};
std::vector<std::string> arr={"G","D","F","E","C","A","B","H"};

x::sort_by(order_by,
              [&]
              (size_t a, size_t b)
              {
                  std::swap(arr.at(a),arr.at(b));
              });
      

x::sort_by facilitates sorting an array by specifying the new order of the values in the array. x::sort_by()'s first parameter is a std::vector<size_t> with strictly increasing values starting with 0, so a vector of size 8 will always have values 0 through 7, in some order.

x::sort_by() sorts the vector in place. x::sort_by()'s second parameter is a closure that takes two size_t parameters, whose values are always two valid vector indexes, and the closure gets called to indicate that the specified values in the vector should be swapped.

Using the closure to invoke std::swap on another vector results in that vector getting sorted accoding to the indexes specified by the first vector. The above examples results in both vector getting sorted.