Difference between `closed_iota` and `iota`?

350 Views Asked by At

What is the difference between closed_iota and iota, from the ranges-v3 library?

2

There are 2 best solutions below

2
On BEST ANSWER

The second one follows the standard C++ way of expressing a range - defaulting to right-hand side open range. The first one is inclusive.

iota takes two arguments: start and end. It produces elements from start to end without including end.

closed_iota takes two arguments: start and end. It produces elements from start to end including end value.

Example: iota(1, 5) represents a range consisting of {1, 2, 3, 4}, and closed_iota(1, 5) represents a range consisting of {1, 2, 3, 4, 5}.

You want both of them because, by default, we expect things to be right-hand side exclusive, but there are times when you want the whole range of values. In that case you need closed_iota.

There are inconsistencies, however - look at std::uniform_xxx_distributions.

0
On

Both closed_iota and iota take 2 arguments, a begin value, and an end value, and produce a range of values containing all the values between begin and end.

The former generates all values from begin to end inclusive, and the latter does the same, but the last value, i.e. end, is excluded.

You might be wondering what the point of closed_iota is, since you could always do this transformation:

// from this
closed_iota(begin, end);
// to this
iota(begin, end + 1);

One reason is this transformation is not always possible. e.g. consider what happens when end is the largest possible int. Then the second version would invoke UB when doing end + 1. You can solve this particular case by using closed_iota.