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


我們知道,當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;
    }
};

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM