We know that when a vector is very large, it can be very time consuming to write the elements in a loop, so is there any way to write the vector to the file at once?
Using the flow operator overloading method can be done, not only the basic type of vector can be written once, the vector storage struct is also possible, here is a simple example, declare the structure of the body:
struct point{ Double// latitude double// longitude Longlong// time }
Write a class wrapper stream operator:
classonepoint{ Public: point P;//Point Public: Friend Ostream&operator<< (ostream& out,Constpoint&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; }};
It should be noted here that the function of the overloaded stream operator should be set to the friend function, because the member of the class two operator overload requires that the left operand of the operator be the first parameter of the operator function, whereas the >> in the Stream class library requires the first argument to be a ostream reference, so it cannot be a member of a class, only as friend.
After declaring it, you can write the entire vector to the file:
ofstream Fout; string " H:\\test.dat " ; Fout.open (Str.c_str (), ios::binary), vector<onepoint> pointset = track.getpointset (); Copy ( Pointset.begin (), pointset.end (), Ostream_iterator<onepoint> (fout)); // write-once fout.close ();
Read in a similar way:
| ios::ate), Vector<onepoint> V (istream_iterator<trackpoint> (IFS)), istream_iterator< Trackpoint> (OFS));
Of course, the previous OnePoint declaration, not the structure is also possible:
classpoint{ Public: DoubleLat//Latitude DoubleLon//LongitudeUnsignedLong LongTime//Time Public: Friend Ostream&operator<< (ostream& out,Constpoint&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; }};
C + + overloaded stream operator, which writes the vector of the storage structure directly to the file