There is a rather typical task of sorting two arrays simultaneously, assuming that same indexed elements of the arrays form virtual pairs, which are sorted. Such questions appear at least 10 years ago: boost zip_iterator and std::sort
Now this task can be solved using range-v3 library:
#include <array>
#include <range/v3/all.hpp>
int main() {
auto x = std::array{ 3, 2, 4, 1 };
auto y = std::array{'A', 'B', 'C', 'D'};
ranges::sort( ranges::views::zip( x, y ) );
// here x = {1,2,3,4}, y={'D','B','A','C'}
}
Online demo: https://gcc.godbolt.org/z/WGo4vGsx5
In C++23 std::ranges::zip_view appears, and my expectation was that the same program can be written using the standard library only:
#include <array>
#include <ranges>
#include <algorithm>
int main() {
auto x = std::array{ 3, 2, 4, 1 };
auto y = std::array{'A', 'B', 'C', 'D'};
std::ranges::sort( std::views::zip( x, y ) );
}
Unfortunately, it results in long compilation errors. E.g. in GCC:
...
/opt/compiler-explorer/gcc-trunk-20221127/include/c++/13.0.0/bits/ranges_algo.h:54:31: error: no matching function for call to '__invoke(std::ranges::less&, std::pair<int, char>&, std::pair<int&, char&>)'
54 | return std::__invoke(__comp,
| ~~~~~~~~~~~~~^~~~~~~~
55 | std::__invoke(__proj, std::forward<_TL>(__lhs)),
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
56 | std::__invoke(__proj, std::forward<_TR>(__rhs)));
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
...
Online demo: https://gcc.godbolt.org/z/47xrzM6ch
Is it just because the implementations are not mature enough yet, or zip view in C++23 will not help to sort two array?
At least the trunk version of libc++ (llvm) supports this:
std::ranges::sort(std::views::zip(x, y), [](auto&& a, auto&& b) {
return std::tie(std::get<0>(a), std::get<1>(a)) <
std::tie(std::get<0>(b), std::get<1>(b));
});
Demo
If you use three ranges instead of two, it works without having to supply a user-defined comparator function:
auto x = std::array{ 3, 2, 4, 1 };
auto y = std::array{'A', 'B', 'C', 'D'};
auto z = std::array{"Z", "Y", "X", "W"};
std::ranges::sort(std::views::zip(x, y, z));
Demo
I assume the version that zips two ranges will not need a user-defined comparator function when fully implemented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With