Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why `copy_n`, `fill_n` and `generate_n`?

Why _n versions of the copy, fill and generate have been provided in C++11, and why only these algorithms?

like image 407
Vincent Avatar asked Mar 13 '14 15:03

Vincent


1 Answers

Alexander Stepanov (original designer of the STL) discusses this issue (amongst many others) in his excellent video series Efficient Programming with Components. He originally proposed a number of other _n variants of STL algorithms but they were not accepted when STL was originally standardized. Some were added back in for C++11 but there are still some that he believes should be available that are missing.

There are a number of reasons why _n variants of algorithms are useful. You may have an input iterator or output iterator which you know can produce or consume n elements but you don't have a way to obtain a suitable end iterator. You may have a container type like a list which you know is big enough for an operation but which doesn't give you an efficient way to obtain an iterator n positions beyond your begin iterator. You may have an algorithm like binary_search / lower_bound which is most naturally expressed in terms of counted ranges. It may just be more convenient when you have n already but you don't have an end iterator and would have to generate one to call the non _n variant of an algorithm.

like image 79
mattnewport Avatar answered Oct 20 '22 22:10

mattnewport