为了方便显示map而自定义的两个函数,出现了一个诡异的问题,感谢jinq????@163.com告之解决方法,但是我对问题的原因还是不太清楚.

#include <map>
#include <string>
#include <iterator>
#include <iostream>

using namespace std;
namespace std    
{    
     //如果不将该函数放入名字空间std则使用ostream_iterator不能通过编译
     //但是可以直接用cout输出pair

    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
)
{
    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;
}
posted on 2007-05-09 13:10 张沈鹏 阅读(1043) 评论(7)  编辑 收藏 引用 所属分类: C++
Comments
  • # re: C++ std名字空间ostream_iterator与的诡异问题
    金庆
    Posted @ 2007-10-13 12:31
    我不记得解答过你的这个问题...
    请不要直接显示我的邮件地址,避免被用于垃圾邮件。  回复  更多评论   
  • # re: C++ std名字空间ostream_iterator与的诡异问题
    Minidx全文检索
    Posted @ 2007-10-13 13:57
    居然还有这样的事情……  回复  更多评论   
  • # re: C++ std名字空间ostream_iterator与的诡异问题
    张沈鹏
    Posted @ 2007-10-13 14:08
    fixed  回复  更多评论   
  • # That's not just the best aswner. It's the bestest answer!
    Fats
    Posted @ 2011-05-26 12:09
    That's not just the best aswner. It's the bestest answer!  回复  更多评论   
  • # More posts of this quality. Not the usual c***, pelase
    Liberty
    Posted @ 2011-05-26 13:28
    More posts of this quality. Not the usual c***, pelase  回复  更多评论   

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理