Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the range-based 'for' loop deprecate many simple algorithms?

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?

like image 684
fredoverflow Avatar asked Jan 10 '13 13:01

fredoverflow


People also ask

Why use range-based for loop?

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.

What is the difference between for range loop and?

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.


1 Answers

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.

like image 60
Bo Persson Avatar answered Oct 30 '22 17:10

Bo Persson