Algorithm solution:
std::generate(numbers.begin(), numbers.end(), rand);
Range-based for-loop solution:
for (int& x : numbers) x = rand();
Why would I want to use the more verbose std::generate
over range-based for-loops in C++11?
Range-based for loop (since C++11) Executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.
The "for" loop For loops can iterate over a sequence of numbers using the "range" and "xrange" functions. The difference between range and xrange is that the range function returns a new list with numbers of that specified range, whereas xrange returns an iterator, which is more efficient.
The first version
std::generate(numbers.begin(), numbers.end(), rand);
tells us that you want to generate a sequence of values.
In the second version the reader will have to figure that out himself.
Saving on typing is usually suboptimal, as it is most often lost in reading time. Most code is read a lot more than it is typed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With