Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this correct way to combine std::generate_n and std::back_inserter?

Tags:

c++

c++11

stl

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.

like image 292
NoSenseEtAl Avatar asked Aug 21 '12 07:08

NoSenseEtAl


1 Answers

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);});
  • Calling mrbig.reserve(nitems) would be more efficient
  • You should use c++03 std::rand or c++11 uniform_int_distribution<> from <random> instead of c rand.
  • The parentheses () between the lambda capture and lambda body are unnecessary for a lambda taking no arguments, although some people prefer them
  • It is not guaranteed that in implementation character set the letters a-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?
like image 65
ecatmur Avatar answered Sep 19 '22 13:09

ecatmur