简体   繁体   中英

How to use std::generate

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?

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) , ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM