Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++: what exactly does &rand do?

This is an excerpt of some c++ code, that i'll have to explain in detail in some days:

std::vector<int> vct(8, 5);

std::generate(vct.begin(), vct.end(), &rand);

std::copy(vct.rbegin(), vct.rend(),
    std::ostream_iterator<int>(std::cout, "\n"));

i think i understand everything about it, except that tiny mystical &rand. what exactly does it do? i mean obviously it produces some kind of pseudo-random-numbers, but they always remain the same. where does the &rand come from? what kind of expression is it? where do the values it produces come from? i'm a bit confused…

also, i could neither find any other occurrences of the word "rand" in the code, nor did i see any code that could have something to do with random numbers. that made me wonder, because my (very limited) experience in c++ showed, that only very few things simply work without having to be declared or included previously.

thanks for helping out!

like image 475
Patrick Oscity Avatar asked Apr 27 '26 11:04

Patrick Oscity


1 Answers

The & in &rand returns the address of the rand() function. You're passing a function pointer to generate() so generate() can call rand() to generate random numbers.

like image 157
Ken Bloom Avatar answered Apr 29 '26 03:04

Ken Bloom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!