Sign in to follow this  

Understanding the code

Recommended Posts

Hi guys, I was going through a few samples of msdn . I found this set of code. I am able to partially understand it. I would need ur help to understand the rest.
Here goes the code
#include <iostream>
#include <numeric>
#include <functional>
#include <vector>
#include <iterator>
#include <string>

using namespace std;

typedef vector < float > FloatArray;
typedef vector < string > StringArray;
typedef ostream_iterator <float, char, char_traits <char> > FloatOstreamIt; 

int main ()
	// a vector of floats
	FloatArray rgFA;

	// an ostream iterator that outputs a float to cout terminated
	// by a space
	FloatOstreamIt OstreamIt(cout,"\n");

	// Initialize the array to 1,1/2,1/3,...
	for (int i=0; i<100; i++) rgFA.push_back(i+1);

	// Print the array
	cout << endl;

	//// Initialize array of strings
	//StringArray rgs;
	//rgs.push_back("This ");
	//rgs.push_back("is ");
	//rgs.push_back("one ");
	//rgs.push_back("sentence. ");

	//// Concatenate the strings in the array and print the sentence
	//cout << "The concatenated vector of strings: "
	//	<< accumulate(rgs.begin(),rgs.end(),string(""))
	//	<< endl;

What i didnt understand was the third parameter in the following line.. typedef ostream_iterator <float, char, char_traits <char> > FloatOstreamIt; what is the char_traits<char> stuff? . First parameter is the input to the custom cout Second is the output Atleast am i right with these two? Thanks and Regards Rohith.H.N

Share this post

Link to post
Share on other sites
Standard library stream objects are template classes. std::ostream is actually a typedef for std::basic_ostream<char, std::char_traits<char> >. When you use an ostream_iterator, the second and third template paramters need to match the template parameters for the stream you're writing to. Since std::cout is a std::ostream, the ostream_iterator has to have char and std::char_traits<char> as the second and third template parameters.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this