Re: ostream_iterator and vector< pair<int, string> >
On Sep 30, 12:17 pm, "subramanian10...@yahoo.com, India"
<subramanian10...@yahoo.com> wrote:
Consider the following piece of code:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <utility>
#include <iterator>
#include <algorithm>
int main()
{
typedef pair<int, string> is;
vector<is> v;
// store values in v
ofstream ofs("output_file_word_count");
ostream_iterator<is> osi(ofs);
copy(v.begin(), v.end(), osi); ------------------------> this line
does not compile.
return 0;
}
Is it possible to print pair<int, string> with
ostream_iterator ?
Yes and no. ostream_iterator requires an operator>>. There is
no operator>> for std::pair< int, std::string >, and no way to
define one in a way that ostream_iterator will can find it. And
of course, you don't want to be able to define one anyway, since
if you could, other developers in the project could as well, and
you'd end up with clashes.
What you can do is define a formatting class, which will convert
implicitly from std::pair< int, std::string >, and use an
ostream_iterator with that. Something like:
class FmtIntStringPair
{
public:
FmtIntStringPair( std::pair< int, std::string > const& obj )
: myObj( &obj )
{
}
friend std::ostream&
operator>>( std::ostream& dest, FmtIntStringPair const& obj )
{
dest << "[" << obj.myObj->first
<< ": " << obj.myObj->second << "]" ;
// Or whatever formatting you want...
return dest ;
}
private:
// Use pointer so assignment is defined...
std::pair< int, std::string > const*
myObj ;
} ;
Then use std::ostream_iterator< FmtIntStringPair > for output.
For example if I had vector<string>, I am able to use
ostream_iterator.
There *is* an >> operator for std::string. In std::, where it
can be found.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34