接上篇,这篇给出vector中存放自己编写的类的源码~
#include <iostream>
#include <vector>
#include <iterator>
#include <sstream>
#include <string>
using namespace std;
class test
{
public:
int a;
string b;
test(){a=0;b="";}
test(int k,string l){a=k;b=l;}
test(const test &t){a=t.a;b=t.b;}
test& operator=(const test &t){
a= t.a;
b= t.b;
return *this;
}
friend inline istream & operator>>(istream & is, test &t1){
is>>t1.a>>t1.b;
return is;
}
friend inline ostream & operator<<(ostream & os,const test &t1){
os<<t1.a;
os<<t1.b;
return os;
}
};
void main()
{
int a = 3,c;
float b = 4.2f,d;
ostringstream s1;
vector<test> v;
vector<test> r;
s1<<a<<" "<<b<<" ";//
v.push_back(test(1,string("dsfk")));
v.push_back(test(2,string("kdsf")));
copy(v.begin(),v.end(),ostream_iterator<test>(s1," ") );//写
string s2 = s1.str();//s2保存的内容为"3,4.2"
cout<<s2<<endl;
istringstream s3(s2);
s3>>c;
s3>>d;
cout<<c<<" "<<d<<" ";
copy(istream_iterator<test>(s3),istream_iterator<test>(),back_inserter(r));//读
copy(r.begin(),r.end(),ostream_iterator<test>(cout," "));
}