Home > OS >  How to use std::generate
How to use std::generate

Time:08-03

https://en.cppreference.com/w/cpp/algorithm/generate

states that it takes Parameters

ForwardIt first, ForwardIt last, Generator g  

and the description is

Assigns each element in range [first, last] a value generated by the given function object g.

so I declared an Array (std::array) with X Elements, where

std::generate(&Arr[0],&Arr[X],[](){...})  

caused a out of bounds violation.
While std::generate(&Arr[0],&Arr[X-1],[](){...}) does not. Note: in a small test program I see that std::generate(&Arr[0],&Arr[X-1],[](){...}) does not initialize the last element

Next I tried to improve with

std::generate(&Arr.front(),&Arr.back(),[&gen](){

Note: same effect here: the last Element is not initialized

but in the Internet you also see

std::generate(Arr.begin(),Arr.end(),[&gen](){

Which compiles fine (and seems to work correctly with initializing the last element)

Now I wonder how Arr.end() and in range [first, last) match, as end() is an Iterator to first out of bounds element, or where I am doing wrong?

CodePudding user response:

You are allowed to form a pointer one past the end of an array, but not dereference it.

For raw arrays, &Arr[X] is defined to be equivalent to &*(Arr X), i.e. you first dereference, then take the address. Containers define [] in terms of a (hidden) raw array.

Similarly begin() and end() will be something like return Arr; and return Arr size; respectively.

  • Related