Home > C++, VC++ > Dumping contents of a vector/list to cout

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…

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] [864] [
stream << lpszMsg << "["; // Get iterator for given stream, every element will be seperated with second // parameter. std::ostream_iterator Itr( stream, "] [" ); // Just one line to dump vector contents, no loops needed std::copy( VecToPrint.begin(), VecToPrint.end(), Itr ); // Remove redundant space and bracket ( " [" ) from the end // After this statement the series will look like [123] [864] stream << "\b\b \b\b\n"; }// End Dump int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { VTVec VecObj( 10000, 0 ); // Fill vector with random number, see earlier post on std::generate std::generate( VecObj.begin(), VecObj.end(), rand ); // Dump to std::cout Dump( VecObj, std::cout, "Dumping vector of ints...\n" ); }// End _tmain[/sourcecode]

Advertisements
  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: