Sorting a std::vector by Values of a Different std::vector
This problem involves aligning the ordering of a vector with the order of another vector. For instance, the vector Index contains numbers [3, 1, 2] and the vector Values contains strings "Third, First, Second." Sorting Index in ascending order ([1, 2, 3]) should result in Values being sorted in the corresponding order (["First", "Second", "Third"]).
Solution:
A common approach involves creating a vector order by combining indices from Index and their corresponding elements from Values. This vector can then be sorted using a custom comparator that compares the elements in Index:
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); struct ordering { bool operator ()(pair<size_t, myiter> const& a, pair<size_t, myiter> const& b) { return *(a.second) < *(b.second); } }; sort(order.begin(), order.end(), ordering());
The resulting order vector now contains the sorted indices. To apply this order to Values, the following function can be used:
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; } Values = sort_from_ref(Values, order);
This function takes the original vector in and the reference vector containing the sorted indices and returns a copy of in sorted accordingly.
The above is the detailed content of How to Sort One `std::vector` Based on the Order of Another?. For more information, please follow other related articles on the PHP Chinese website!