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.
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.
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