Page 28 - MSDN Magazine, October 2017
P. 28
C++
From Algorithms to
Coroutines in C++
Kenny Kerr
There’s a C++ Standard Library algorithm called iota that has always intrigued me. It has a curious name and an interesting function. The word iota is the name of a letter in the Greek alpha- bet. It’s commonly used in English to mean a very small amount and often the negative, not the least amount, derived from a quote in the New Testament Book of Matthew. This idea of a very small amount speaks to the function of the iota algorithm. It’s meant to fill a range with values that increase by a small amount, as the initial value is stored and then incremented until the range has been filled. Something like this:
#include <numeric>
int main() {
int range[10];
// Range: Random missile launch codes
std::iota(std::begin(range), std::end(range), 0);
// Range: { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } }
It’s often said that C++ developers should expunge all naked for loops and replace them with algorithms. Certainly, the iota algo- rithm qualifies as it takes the place of the for loop that any C or
C++ developer has undoubtedly written thousands of times. You can imagine what your C++ Standard Library implementation might look like:
namespace std {
template <typename Iterator, typename Type>
void iota(Iterator first, Iterator last, Type value) {
for (; first != last; ++first, ++value) {
*first = value; }
}
So, yeah, you don’t want to be caught in a code review with code like that. Unless you’re a library developer, of course. It’s great that the iota algorithm saves me from having to write that for loop, but you know what? I’ve never actually used it in production. The story usually goes something like this: I need a range of values. This is such a fundamental thing in computer science that there must be a standard algorithm for it. I again scour the list over at bit.ly/2i5WZRc and I find iota. Hmm, it needs a range to fill with values. OK, what’s the cheapest range I can find ... I then print the values out to make sure I got it right using ... a for loop:
#include <numeric> #include <stdio.h>
int main() {
int range[10];
std::iota(std::begin(range), std::end(range), 0);
for (int i : range) {
printf("%d\n", i); }
}
To be honest, the only thing I like about this code is the range- based for loop. The problem is that I simply don’t need nor want that range. I don’t want to have to create some container just to hold
}
This article discusses:
• Introduction to the iota algorithm
• The built-in range function in Python
• Attempts to avoid raw loops
• Using coroutines to write algorithms
Technologies discussed:
C++, Algorithms, Python, Iterators, Generators, Coroutines
Code download available at:
godbolt.org/g/NXHBZR
24 msdn magazine