返回信息流想写一个打印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"));
这是一条镜像帖。来源:北邮人论坛 / cpp / #67257同步于 2012/12/12
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
[问题]如何打印pair【更新问题2】
wangkendy
2012/12/12镜像同步9 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
template <typename T, typename U>
ostream& operator<<(ostream& os, const pair<T, U>& pair)
{...}
namespace std
{
template<class T1,class T2>
ostream& operator<<(ostream &os,const pair<T1,T2> &p)
{
os<<p.first<<":"<<p.second<<endl;
return os;
}
}
能给解释一下为什么一定要加namespace std吗?多谢。
【 在 gsl2011 的大作中提到: 】
: namespace std
: {
: template<class T1,class T2>
: ...................
【 在 guoguoshuai 的大作中提到: 】
: 能给解释一下为什么一定要加namespace std吗?多谢。
:
由于其受限于ADL,查找到std为止。
其实在std中重载operator并不是好的办法,可以通过定义MyType、transform、for_each等多种方法解决。
在网上查了半天,又看了Thinking in c++,终于明白了ADL,多谢。
【 在 gsl2011 的大作中提到: 】
: 由于其受限于ADL,查找到std为止。
: 其实在std中重载operator并不是好的办法,可以通过定义MyType、transform、for_each等多种方法解决。
【 在 guoguoshuai 的大作中提到: 】
: 在网上查了半天,又看了Thinking in c++,终于明白了ADL,多谢。
:
呵呵,不好意思哈,你可以直接问的~ 不过自己查肯定会记得更清楚的~