[cpp] 涓轰肻涔ꢜ蟨骮涔炉air瀵逛躺ostrem髧 9860;lt;<杩鞮绗躐,瀵涹ap涓꾏浠ョꢔcopy杩財杈몇?
寮袲楣⢏铧靛邭绉ぇ 澶 1090;覸)
zsp007 at gmail.com
Mon May 7 22:31:26 CST 2007
为什么在自定义pair对于ostrem的<<运算符后,对map不可以用copy进行输出?
//copy不能通过编译
//报错:d:\ungreen\vs2005\vc\include\iterator(308) : error C2679:
二进制"<<": 没有找到接受"const std::pair<_Ty1,_Ty2>"类型的右操作数的运算符(或没有可接受的转换)
//copy(m.begin(), m.end(), ostream_iterator<pair<K,V> >(s, "\n"));
改为以下代码就可以通过编译了
for(map<K,V>::const_iterator i=m.begin();i!=m.end();++i)s<<*i<<"\n";
下面是完整的源代码
#include <map>
#include <string>
#include <iterator>
#include <algorithm>
#include <iostream>
using namespace std;
template<class _Elem,class _Traits,class K,class V>
basic_ostream<_Elem,_Traits>& operator<<(
basic_ostream<_Elem,_Traits>& s
,
const pair<K,V>& p
)
{
return s<<p.first<<" : "<<p.second;
}
template<class _Elem,class _Traits,class K,class V>
basic_ostream<_Elem,_Traits>& operator<<(
basic_ostream<_Elem,_Traits>& s
,
const map<K,V>& m
)
{
//for(map<K,V>::const_iterator i=m.begin();i!=m.end();++i)s<<*i<<"\n";
copy(m.begin(), m.end(), ostream_iterator<pair<K,V> >(s, "\n"));
return s;
}
int main()
{
using namespace std;
map<string,string> a;
a["key1"]="value1";
a["key2"]="value2";
cout<<a;
system("pause");
return 0;
}
--
Hi , I'm Earth-Man.
你好,我是地球人。
欢迎访问我的博客:
http://zsp.javaeye.com/
--张沈鹏
More information about the Cpp
mailing list