Sorting Zipped Containers in C Using Boost or the STL
Introduction
This question explores the challenge of sorting multiple vectors or containers together, maintaining their element correspondence, without copying them. The goal is to achieve this without relying on tuples or other temporary data structures.
Original Question
The original question poses a specific task: sorting three vectors, while ensuring that the elements in each vector are rearranged in the same order. It explicitly excludes copying the vectors into a tuple or implementing a custom sorting function. Attempts to use boost::zip_iterator or boost::zip_range were unsuccessful due to the read-only and non-random access nature of the iterators.
Answer
A working solution was provided by interjay, leveraging the tupleit.hh library:
// tupleit.hh included for custom tuple iterators #include <tupleit.hh> template <typename... T> auto zip(T&... containers) -> boost::iterator_range<decltype(iterators::makeTupleIterator(std::begin(containers)...))> { return boost::make_iterator_range(iterators::makeTupleIterator(std::begin(containers)...), iterators::makeTupleIterator(std::end(containers)...)); }
This template function combines containers into a boost::iterator_range that behaves like a tuple iterator, allowing for sorting using boost::sort:
boost::sort( zip(a, b, c), [](tup_t i, tup_t j){ return i.get<0>() > j.get<0>(); });
Future Considerations
The answer works for sequence containers (e.g., vectors), but it would be desirable to extend it to sortable containers, which require random_access and bidirectional TupleIterators. However, the standard sort algorithm does not currently support BidirectionalIterators.
Update
Mixing sequence-like containers (e.g., sequences and lists) is currently possible. However, incorporating lists would require a sort algorithm that operates on BidirectionalIterators, which is not currently available in the standard library.
The above is the detailed content of How Can I Sort Multiple Vectors in C Simultaneously Without Copying, Using Boost or the STL?. For more information, please follow other related articles on the PHP Chinese website!