C++重載流運算符,將存儲結構體的vector直接寫入文件

咱們知道,當vector很大的時候,若是使用循環的方式將其中的元素寫入文件將很是費時,所以有沒有辦法將vector一次性寫入文件呢?ios

採用流運算符重載的方法能夠作到,不只基本類型的vector能夠一次性寫入,存儲struct的vector也是能夠的,這裏舉一個簡單的例子,聲明結構體:函數

struct point
{
    double lat; //緯度
    double lon; //經度
    unsigned long long time; //時間
}

寫一個類封裝流運算符:spa

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的引用,因此不能做爲類成員,只能做爲友元.code

聲明好之後就能夠將整個vector寫入文件了:blog

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();

讀取的方式相似:get

ifstream ifs(Path, ios::binary);
ifstream ofs(Path, ios::binary | ios::ate);
vector<onepoint> v((istream_iterator<trackpoint>(ifs)), istream_iterator<trackpoint>(ofs));

固然前面的onepoint聲明,不要結構體也是能夠的:string

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;
    }
};
相關文章
相關標籤/搜索