Introduction
The task of simultaneously sorting multiple vectors while maintaining their inter-element correspondence is a common challenge in programming. This article explores solutions to this problem using either the Boost library or the Standard Template Library (STL).
Standard Approach
The standard approach involves extracting the values from the vectors into a composite data structure, such as a tuple or struct. This approach, however, requires copying the data, which can be inefficient.
Boost Solution
Boost provides the boost::zip_iterator and boost::zip_range that enable the creation of iterators that traverse multiple containers in parallel. However, these iterators are read-only and not random access, which limits their use with standard sorting algorithms.
Range-v3 Solution
One solution is to use the range-v3 library. The view::zip function creates a view that iterates over multiple containers in parallel. This view allows for sorting using the ranges::sort function.
#include <range/v3/all.hpp> #include <iostream> int main() { std::vector<int> v1 = {15, 7, 3, 5}; std::vector<int> v2 = {1, 2, 6, 21}; ranges::sort(ranges::view::zip(v1, v2), std::less<>{}, &std::pair<int, int>::first); std::cout << ranges::view::all(v1) << '\n'; std::cout << ranges::view::all(v2) << '\n'; return 0; }
This code demonstrates how to sort two vectors simultaneously while maintaining the element correspondence. The sorted result is printed to the console.
Future Considerations
Although this approach works well for sequences, extending it to support other container types, such as lists, requires bidirectional and random access iterators. Currently, the STL's std::sort function does not support bidirectional iterators.
The above is the detailed content of How to Efficiently Sort Multiple Vectors Simultaneously in C While Preserving Correspondence?. For more information, please follow other related articles on the PHP Chinese website!