In my quest :) to use as much of STL as I can I came to wonder is it possible to use std::generate and std::back_inserter combined so that I can do the same thing as the following code :
static const size_t nitems=1024*1024;
std::string mrbig;
for (size_t pos=0; pos<nitems; ++pos)
mrbig.push_back('a'+ (rand()%26));
I tried
std::generate_n(std::back_inserter(mrbig),nitems,[](){return 'a'+(rand()%26);});
and it seems to work OK, but I would like to be sure Im not messing up something.
generate_n
requires that its first argument satisfy OutputIterator
, which back_insert_iterator
does (its iterator_category
is output_iterator_tag
).
Potential issues with your code:
std::generate_n(std::back_inserter(mrbig),nitems,[](){return 'a'+(rand()%26);});
mrbig.reserve(nitems)
would be more efficientstd::rand
or c++11 uniform_int_distribution<>
from <random>
instead of c rand
.()
between the lambda capture and lambda body are unnecessary for a lambda taking no arguments, although some people prefer thema-z
form a contiguous block; for example, in EBCDIC, i
and j
are not adjacent. I believe the only portable form is to store a string "abcd...xyz"
in your program and index into it: How can I write a single for loop running from a to z and A to Z in C?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With