Container Algorithms -- Eric Niebler

eric-niebler-toronto.PNGSome more details about the Ranges proposal that was well received by the ISO C++ committee at this month's meeting in Urbana-Champaign:

Container Algorithms

by Eric Niebler

From the article:

... So to sum up, in the world of N4128, we have this:

  • Eager algorithms that can mutate but that don’t compose.
  • Lazy algorithms that can’t mutate but do compose.

Whoops! Something is missing. If I want to read a bunch of ints, sort them, and make them unique, here’s what that would look like in N4128:

extern std::vector<int> read_ints();
std::vector<int> ints = read_ints();
std::sort(ints);
auto i = std::unique(ints);
ints.erase(i, ints.end());

Blech! A few people noticed this shortcoming of my proposal. A week before the meeting, I was seriously worried that this issue would derail the whole effort. I needed a solution, and quick.

Container Algorithms

The solution I presented in Urbana is container algorithms. These are composable algorithms that operate eagerly on container-like things, mutating them in-place, then forwarding them on for further processing. For instance, the read+sort+unique example looks like this with container algorithms:

std::vector<int> ints =
    read_ints() | cont::sort | cont::unique;

Much nicer. Since the container algorithm executes eagerly, it can take a vector and return a vector. The range views can’t do that...

Add a Comment

Comments are closed.

Comments (2)

0 0

Viktor Sehr said on Nov 25, 2014 09:21 AM:

My (unfinshed, and probably never will be) library https://github.com/gloinart/UnderscoreCPP builds upon this concept.

However, if I was the power to redesign the language fundamentals, not just the libraries, I think it would be really useful if C++ could be extended with some sort of piping operator which simply grabs the left argument and pipes it as the first parameter to the right.

myClass.SetVector(my_vector | std::move);
const double rounded = myDouble | std::round;


/Viktor
0 0

Anders Sjögren said on Nov 26, 2014 06:37 AM:

It seems in spirit close to streams, where one alters the stream on the way (e.g. by "<<":ing in data) and getting the same stream out again. Nice!