4

C++ standard does NOT guarantee that std::generate assigns elements in sequential order, but this severely limits its usefulness. In that case, I can only think of two possible uses:

A functor which returns a constant value. But you could just use std::fill.

Filling a data structure with random or arbitrary values not guaranteed to be reproducible from the same seed.

Other than that, what are some non-trivial uses of std::generate that conform to the C++ standard?

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91
  • *"C++ standard does NOT guarantee that std::generate assigns elements in sequential order"* Are you sure this isn't an oversight? It takes only ForwardIterators.. and `generate_n` takes only an OutputIterator – dyp Jun 21 '14 at 22:43
  • While I agree with your contention from a strictly theoretical point, you can easily circumvent the problem by implementing your own version that guarantees that the elements are assigned in a sequential order. – R Sahu Jun 21 '14 at 22:45
  • 1
    .... why does `generate` take ForwardIterators anyway? Why is multi-pass required? Oh, wait, it probably does not require multi-pass, but comparison (which OutputIterator does not provide). So the assumption that it does not guarantee sequential order is probably just a misunderstanding. – dyp Jun 21 '14 at 22:49
  • @dyp for_each guarantees order, but generate does not. – Neil Kirk Jun 21 '14 at 22:57
  • Write a unit test that asserts in-order and just assume that it does. Would anything else ever make sense? – Martin Ba Jun 22 '14 at 10:10
  • @TemplateRex The linked question does not answer my question. It does not list any possible uses of generate other than random number generation. – Neil Kirk Jul 02 '14 at 20:28
  • @NeilKirk the answer by ecatmur shows how to adapt `iota()` (which does have the sequential guarantee) to get a sequential `generate()`, this should lift the limitations for which you seek a solution – TemplateRex Jul 02 '14 at 20:58
  • @TemplateRex That is helpful, thank you. But I'm also curious, assuming this wasn't an error by the standards committee, what they intended non-sequential generate to be used for. – Neil Kirk Jul 02 '14 at 21:19
  • Well pre-C++11 there were no threads so sequentiality was merely a QoI issue (code would run slower, so why worry), maybe that played a role. And in general, the Committee wants to give implementors freedom to implement. There were [similar issues with the guarantees of `std::transform`](http://www.angelikalanger.com/Articles/Cuj/03.ForeachTransform/ForEachTransform.html). You could search the Standards working papers to see if there were old proposals on this topic. – TemplateRex Jul 02 '14 at 21:29
  • Btw i just discovered, the paper I linked to mentions in footnote [5] that `generate` used to have a sequential guarantee! – TemplateRex Jul 02 '14 at 21:33

0 Answers0