Home > C++, VC++ > Filling out a vector using generate function

Filling out a vector using generate function

Let us suppose that you want to fill out a vector with 10000 random elements, phew. Hmm so what you would do is to write a for loop, iterate through, and fill out the elements.

Well I can do it with just one line of code. 🙂 Look

// Typedefs
typedef int VtElem;
typedef std::vector<vtelem> Vector;
const Vector::size_type Size = 10000;

Vector VecObj( Size );
// Look at the last parameter, it needs a callback function pointer/function object/functor,
// we've given standard c "rand" function to fill out vector with random elements.
std::generate( VecObj.begin(), VecObj.end(), rand );

So now we have a vector that has been randomly been filled out. We can replace rand with any kind of filling in method. You can even have a vector full of prime numbers using a prime functor.

There is another version of std::generate called std::generate_n, which as the name suggests generates upto n elements.

Looks like this…

// Fill just 10 elements with random numbers
std::generate_n( VecObj.begin(), 10, rand );

Advertisements
Categories: C++, VC++ Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: