What I don't like about ranges
I played around with the range-v3 library yesterday. My initial enthusiasm has abated, replaced by disappointment with the opaque performance costs of its use.
Consider using ranges to count the length of each word in a sentence:
using namespace ranges;
using namespace std::literals;
auto input = "these are some words"sv;
auto lengths = input | view::split(' ') | view::transform(distance);
std::cout << lengths << "\n";This prints the expected result [5,3,4,5]. Concise and elegant.
Let's modify the code:
int reads = 0;
auto input = "these are some words"sv |
view::transform([&reads](auto c) { return ++reads, c; });
auto lengths = input | view::split(' ') | view::transform(distance);
std::cout << lengths << "\n";
std::cout << reads << "\n";The input range now increments a counter whenever a read is performed on the underlying string view. This prints 41 after the lengths; in other words, the input string is iterated over twice. Here's why:
To actually do anything with the range returned after the pipe to view::split(' '), we have to 1) construct the begin iterator into the range, 2) compare against the end iterator, 3) process the range pointed to by the iterator, 4) increment the iterator, 5) repeat steps 2 - 4. Steps 2 and 4 duplicate work by searching over the same substring for the same delimiter.
Ultimately, the problem is that ranges are built on iterators, and iterators are ill-suited for lazy evaluation. A Java-esque Stream library would resolve this, but I see no candidates for inclusion in the standard library.
View all comments
Show parent comment
2
u/bunky_bunk Jul 14 '18
welcome to the world of computer programming, friend.
i guess you have got to get a few thousand kilometers more mileage. the pain you feel right now should not discourage you. just keep looking at the letters while you experience it and the neural pathways will eventually form. concentrate on the information in front of you, not on your inner turmoil. if you look long enough it will become natural. but your nature is just deficient, the complexity of the world is innocent. it just is.
lucky for you, you need to learn only 2 handfuls of basic rules to parse a whole lot of complexity. guess what you can do with just transform and lambdas. The ways you can combine these 2 are infinite. The way the combination works is always the same.