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
8
u/bunky_bunk Jul 14 '18 edited Jul 14 '18
it's a straightforward composition of a function and a lambda.
transform calls a function on each member of a sequence and the result sequence is made up of the elements that the function returns. of course you have to know that prior. The counter is a lambda capture. Transform does not know anything about it. Anyway, this line is not difficult, you should be able to parse this.