Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't a range be sorted in range-v3?

Tags:

c++

c++20

Using the Range-v3 (release 0.10.0) library I was trying to construct a range from a std::vector, transform it into another range and finally sort that range. I expected the sort step to produce another range that I could consume later. But the best I could come up with was this:

std::vector<std::string> const input { "2", "3", "1" };
using namespace ranges;
std::vector<int> output = input
    | views::transform([](std::string s) { return std::stoi(s); })
    | to<std::vector>()
    | actions::sort

Notice the use of to<std::vector>() after the transform step and before the sort step. This seems to allocate a new std::vector when all I wanted was to sort the range that the transform step had produced.

Why is there no view::sort ? It would fit nicely in the above composition of ranges.

like image 920
Angle.Bracket Avatar asked Jan 26 '23 07:01

Angle.Bracket


1 Answers

The transformed range is only a view, the elements are generated one at a time as the view is iterated. It can't be sorted as there is nowhere to store the sorted elements. A hypothetical implementation would also be inefficient as it would have to transform each element every time it needed to do a comparison for the sort.

Your solution is correct to store the transformed elements in a vector then sort them.

like image 123
Alan Birtles Avatar answered Feb 08 '23 10:02

Alan Birtles