Home >Backend Development >C++ >How to Sort Multiple Vectors Consistently Based on a Reference Vector?
Consider a scenario where you have multiple vectors of the same length and need to sort one of the vectors while maintaining the same sorting order across all the other vectors. This might be useful when the sorted values serve as references for the elements in the other vectors.
In the provided code snippet, we have two vectors: Index and Values. Index contains integers denoting the desired sorting order, and Values contains strings that will be sorted accordingly.
One approach is to create a vector of pairs that combines the elements of Index and Values, and then sort this vector using a custom comparator. Here's how you would do it:
using myiter = std::vector<int>::const_iterator; std::vector<std::pair<size_t, myiter>> order(Index.size()); size_t n = 0; for (const auto& it : Index) { order[n++] = std::make_pair(n, it); } struct ordering { bool operator()(const std::pair<size_t, myiter>& a, const std::pair<size_t, myiter>& b) { return *a.second < *b.second; } }; std::sort(order.begin(), order.end(), ordering());
The order vector now contains the elements from Index and Values in the sorted order. You can use this to sort the other vectors as well. Here's a function template that does that:
template <typename T> std::vector<T> sort_from_ref( const std::vector<T>& in, const std::vector<std::pair<size_t, myiter>>& reference ) { std::vector<T> ret(in.size()); size_t size = in.size(); for (size_t i = 0; i < size; ++i) ret[i] = in[reference[i].first]; return ret; }
Using this function, you can now obtain the sorted version of Values based on the order specified by Index:
std::vector<std::string> sortedValues = sort_from_ref(Values, order);
This approach allows you to efficiently sort multiple vectors in a consistent manner without the need for complex and iterative solutions.
The above is the detailed content of How to Sort Multiple Vectors Consistently Based on a Reference Vector?. For more information, please follow other related articles on the PHP Chinese website!