Cout的扩展
写这个笔记完全是由一道题起的,题目就是如何用iostream迭代器实现类及容器的输出(想必大家早已厌烦了写一个while或for循环来做这件事吧,而且这样做函数基本都是专用,不能实现通用)。(结合C++Primer 第11章)
最初尝试代码如下:
#include<iostream>
#include<fstream>
#include<vector>
#include<algorithm>
#include<iterator>
#include<string>
using namespace std;
template<class T,classbaseType>
void Show(T &v,baseType r)
{
//第二个参数仅仅是为了传递类型
ostream_iterator<baseType>out(cout," ");
copy(v.begin(),v.end(),out);
cout<<endl;
}
template<class T>
void Show(T &v)
{
Show(v,v[0]); //注意重载函数时,常量引用和非常量引用是不同函数
}
int main()
{
vector<string> vec(10,"Bosch");
Show(vec,string(""));
Show(vec);
return 0;
}
|
1) ostream_iterator<baseType> out(cout," ")是声明一个ostream迭代器,其声明将baseType类型的对象写到输出流cout(此处为标准输出,也可以是其它输出流)的ostream_iterator对象,在写入过程中,使用delim作为元素的分隔。Delim是以空字符结束字符数组。
2) copy(v.begin(),v.end(),out),则是将类型T中的在迭代器对范围内的元素拷贝到out所迭代的输出流中。
3) 这个函数实现了输出任何一维容器的功能(当然容器中必须存储基础类型)。
输出一维成功后,我尝试了一下二维容器,结果不甚理想,会在编译期报出类似找不到匹配的“<<“操作符的错误,先看程序:
#include<iostream>
#include<fstream>
#include<vector>
#include<algorithm>
#include<iterator>
#include<string>
using namespace std;
template<class T,class baseType>
void Show(T &v,baseType r)
{
ostream_iterator<baseType> out(cout," ");
copy(v.begin(),v.end(),out);
cout<<endl;
}
template<class T>
void Show(T &v)
{
Show(v,v[0]);
}
int main()
{
vector<string> vec(10,"Bosch");
Show(vec,string(""));
Show(vec);
vector<vector<string> > dvec(2,vec);
Show(dvec[0],string(""));
Show(*dvec.begin(),string(""));
Show(dvec,vec);
ostream_iterator< vector<string> > out(cout," ");
copy(dvec.begin(),dvec.end(),out);
}
|
Show(dvec,vec);
copy(dvec.begin(),dvec.end(),out);
上面两句话编译不通过,而且出来很大篇幅错误,真是无语,我是看不懂了。后经有经验的程序员高人指点,说是“<<“无法找到匹配的,我开始有了概念,大概是没有输出vector<string>类型的操作符重载,那么很自然的想到重载cout。说做就做,见下面程序。
#include<iostream>
#include<fstream>
#include<vector>
#include<algorithm>
#include<iterator>
#include<string>
using namespace std;
ostream& operator << (ostream& os,vector<string>&vec)
{
vector<string>::iterator iter = vec.begin();
while (iter != vec.end())
{
os<<*iter++<<" 0 ";
}
os<<endl;
return os;
}
template<class T,class baseType>
void Show(T &v,baseType r)
{
ostream_iterator<baseType> out(cout," ");
copy(v.begin(),v.end(),out);
cout<<endl;
}
template<class T>
void Show(T &v)
{
Show(v,v[0]);
}
int main()
{
vector<string> vec(10,"Bosch");
Show(vec,string(""));
Show(vec);
cout<<vec;
vector<vector<string> > dvec(2,vec);
Show(dvec[0],string(""));
Show(*dvec.begin(),string(""));
ostream_iterator< vector<string> > out(cout," ");
copy(dvec.begin(),dvec.end(),out);
Show(dvec,vec);
}
|
copy(dvec.begin(),dvec.end(),out);
Show(dvec,vec);
这两行仍然编译不通过,提示错误相同,还是找不到匹配的“<<“操作符,这样我着实郁闷。现在只能是copy内部有问题了,在stackoverflow网站找到了代码: