BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #67257同步于 2012/12/12
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

[问题]如何打印pair【更新问题2】

wangkendy
2012/12/12镜像同步9 回复
想写一个打印pair的函数模板,以下代码编译都过不去!请问该怎么改? #include <iostream> using namespace std; template<typename Pair> ostream& operator<<(ostream& os, const Pair& p) { return os << p.first << ":" << p.second << endl; } int main() { pair<int,int> pii(12, 34); pair<int,float> pif(12, 34.56); cout << pii << endl; cout << pif << endl; return 0; } 感谢两位的解答@iFadeToBlack @gsl2011 问题2:如果想要用copy()输出,该如何写输出的模板函数。 map<int, int> mii; mii.insert(make_pair(12, 34)); mii.insert(make_pair(23, 56)); //... copy(mii.begin(), mii.end(), ostream_iterator<pair<int,int> >(cout, "\n"));
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
iFadeToBlack机器人#1 · 2012/12/12
template <typename T, typename U> ostream& operator<<(ostream& os, const pair<T, U>& pair) {...}
gsl2011机器人#2 · 2012/12/12
namespace std { template<class T1,class T2> ostream& operator<<(ostream &os,const pair<T1,T2> &p) { os<<p.first<<":"<<p.second<<endl; return os; } }
gsl2011机器人#3 · 2012/12/12
我给你的代码就成吧
iFadeToBlack机器人#4 · 2012/12/18
我觉得lz先找本模板的书看看比较好 (好吧,其实是我没看懂你想写什么)
fuxiang90机器人#5 · 2012/12/19
2 楼即可
guoguoshuai机器人#6 · 2013/1/4
能给解释一下为什么一定要加namespace std吗?多谢。 【 在 gsl2011 的大作中提到: 】 : namespace std : { : template<class T1,class T2> : ...................
gsl2011机器人#7 · 2013/1/4
【 在 guoguoshuai 的大作中提到: 】 : 能给解释一下为什么一定要加namespace std吗?多谢。 : 由于其受限于ADL,查找到std为止。 其实在std中重载operator并不是好的办法,可以通过定义MyType、transform、for_each等多种方法解决。
guoguoshuai机器人#8 · 2013/1/5
在网上查了半天,又看了Thinking in c++,终于明白了ADL,多谢。 【 在 gsl2011 的大作中提到: 】 : 由于其受限于ADL,查找到std为止。 : 其实在std中重载operator并不是好的办法,可以通过定义MyType、transform、for_each等多种方法解决。
gsl2011机器人#9 · 2013/1/5
【 在 guoguoshuai 的大作中提到: 】 : 在网上查了半天,又看了Thinking in c++,终于明白了ADL,多谢。 : 呵呵,不好意思哈,你可以直接问的~ 不过自己查肯定会记得更清楚的~