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 );