Sorting a Vector by Values from a Different Vector
Consider the scenario where you have multiple vectors of equal length and aim to sort one vector based on the values from a different vector. For instance, you may have a vector Index of integers and a vector Values of strings. Sorting the Index vector should subsequently reorder the elements in the Values vector accordingly.
One effective approach is to create a vector that pairs the elements from the Index vector with their corresponding indices. This vector, order, can then be sorted using a custom ordering function that compares the elements from the Index vector. The sorted order vector captures the desired sorting order.
Using this sorting order, you can reorder the other vectors. Consider the following code snippet:
typedef vector<int>::const_iterator myiter; vector<pair<size_t, myiter>> order(Index.size()); size_t n = 0; for (myiter it = Index.begin(); it != Index.end(); ++it, ++n) order[n] = make_pair(n, it); sort(order.begin(), order.end(), ordering());
The ordering function sorts the order vector based on the values from the Index vector. You can then use the order vector to reorder the Values vector using the following code:
template <typename T> vector<T> sort_from_ref( vector<T> const& in, vector<pair<size_t, myiter>> const& reference ) { vector<T> ret(in.size()); size_t const size = in.size(); for (size_t i = 0; i < size; ++i) ret[i] = in[reference[i].first]; return ret; }
This approach allows you to sort one vector by the values from another vector and apply the same sorting to additional vectors.
The above is the detailed content of How to Sort One Vector Based on the Values of Another Vector?. For more information, please follow other related articles on the PHP Chinese website!