Reading contents of a file to a vector at one go!

It’s quite easy to read the contents of a file to a vector at one go. For this we need to get the size of a file and ask vector to allocate a buffer to hold these many bytes (use vector::resize()). Here is a function which does this. Note that it’s a byte/char vector. [sourcecode […]
Continue reading…

 

What’s the size limit of a vector?

Use std::vector::max_size() function. Don’t confuse this function with std::vector::capacity() and std::vector::size() functions. vector::capacity() tells us when a vector will be reallocated and vector::size() tells us the count of elements inserted into a vector. Source code of vector::max_size looks like this… [sourcecode language=’cpp’]_SIZT max_size() const _THROW0() {    // estimate maximum array size    _SIZT _Count […]
Continue reading…

 

Dumping contents of a vector/list to cout

Is it possible to do this with just one line of code? Oh yes! Have a look… [sourcecode language=”cpp”]typedef int VT; typedef std::vector VTVec; void Dump( VTVec& VecToPrint, std::ostream& stream, const char* lpszMsg ) { // We will be wrapping every element within a square bracket. // In the end output looks like this… [123] […]
Continue reading…

 

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 [sourcecode language=”cpp”]// Typedefs typedef int VtElem; typedef […]
Continue reading…

 

Initializing vector elements to a particular value

There are 8 constructors for std::vector class, out of which there is this constructor that takes two parameters… [sourcecode language=”cpp”]vector( size_type _Count,  const Type& _Val );[/sourcecode] First parameter is size of the vector, second is default value for all elements in the vector. Let’s suppose you have 1000 Employees in your organization each of them has an initial […]
Continue reading…

 

Using std transform function

So what does std::transform function do? “Applies a specified function object to each element in a source range or to a pair of elements from two source ranges and copies the return values of the function object into a destination range.” Some general applications of using transform is as follows… For doing some kind of operation […]
Continue reading…