I've used an ostream_iterato r over other types and had no problem.
However, with the following code snippet, I'm getting a compiler
error, and I'm stymied as to why. It's seems to be related to the
string type, because iterating over pairs of other types has worked
fine for me. The (rather verbose) error is:
/usr/include/c++/4.2/bits/stream_iterator .h:196: error: no match for
'operator<<' in '*((std::ostrea m_iterator<std: :pair<unsigned int,
std::basic_stri ng<char, std::char_trait s<char>, std::allocator< char
>, char, std::char_trait s<char*)this)-std::char_trait s<char>, std::allocator< char >, char,
std::ostream_i terator<std::pa ir<unsigned int, std::basic_stri ng<char,
std::char_trait s<char::_M_stre am << __value'
Thanks,
Shaun
#include <iostream>
#include <iterator>
#include <set>
#include <string>
using namespace std;
ostream& operator <<(ostream& o, const pair<unsigned, string>& age)
{
return o << age.second << ": " << age.first;
}
int main()
{
string a("Alice");
string b("Bob");
string c("Carol");
pair<unsigned, stringpa(19, a);
pair<unsigned, stringpb(17, c);
pair<unsigned, stringpc(23, b);
set<pair<unsign ed, string ages;
ages.insert(pa) ;
ages.insert(pb) ;
ages.insert(pc) ;
ostream_iterato r<pair<unsigned , string oi(cout, ", ");
copy(ages.begin (), ages.end(), oi);
cout << '\n';
return 0;
}