我们知道,当vector很大的时候,如果使用循环的方式将其中的元素写入文件将非常费时,因此有没有办法将vector一次性写入文件呢?
采用流运算符重载的方法可以做到,不仅基本类型的vector可以一次性写入,存储struct的vector也是可以的,这里举一个简单的例子,声明结构体:
struct point { double lat; //纬度 double lon; //经度 unsigned long long time; //时间 }
写一个类封装流运算符:
class onepoint{ public: point p;//点 public: friend ostream& operator<< (ostream& out, const point& point) { //out << point.lon<<","<<point.lat<<","<<point.time<<endl; out.write((char*) &point,sizeof(point)); return out; } friend istream& operator>>(istream& is, point& point) { is.read((char*) &point,sizeof(point)); return is; } };
这里需要注意,重载流运算符的函数应设为友元函数,因为类的成员二元运算符重载要求运算符左操作数为运算符函数的第一个参数,而流类库中的>>则要求第一个参数为ostream的引用,所以不能作为类成员,只能作为友元.
声明好以后就可以将整个vector写入文件了:
ofstream fout; string str = "H:\\test.dat"; fout.open(str.c_str(),ios::binary); vector<onepoint> pointset = track.getPointSet(); copy( pointset.begin(), pointset.end(), ostream_iterator<onepoint>(fout));//一次性写入 fout.close();
读取的方式类似:
ifstream ifs(Path, ios::binary); ifstream ofs(Path, ios::binary | ios::ate); vector<onepoint> v((istream_iterator<trackpoint>(ifs)), istream_iterator<trackpoint>(ofs));
当然前面的onepoint声明,不要结构体也是可以的:
class point{ public: double lat; //纬度 double lon; //经度 unsigned long long time; //时间 public: friend ostream& operator<< (ostream& out, const point& point) { //out << point.lon<<","<<point.lat<<","<<point.time<<endl; out.write((char*) &point,sizeof(point)); return out; } friend istream& operator>>(istream& is, point& point) { is.read((char*) &point,sizeof(point)); return is; } };
时间: 2024-10-25 15:06:57