C++重载流运算符,将存储结构体的vector直接写入文件

这篇博客介绍了如何使用流运算符重载的方法,实现大vector的高效写入和读取文件。通过定义一个结构体point和一个类onepoint,重载了<<和>>运算符,使得能够一次性将包含point结构体的vector写入和从二进制文件读取。这种方法对于处理大量数据时能显著提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们知道,当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 = "test.dat";
fout.open(str.c_str(),ios::binary);
vector<onepoint> pointset;
// poinset.push_back(...);			// 添加相应的元素
// poinset.push_back(...);
// ...
// ...
// poinset.push_back(...);
// poinset.push_back(...);
copy( pointset.begin(),  pointset.end(), ostream_iterator<onepoint>(fout));//一次性写入
fout.close();

从文件中读取vector:

ifstream ifs(Path, ios::binary);
ifstream ofs(Path, ios::binary | ios::ate);
vector<onepoint> v((istream_iterator<onepoint>(ifs)), istream_iterator<onepoint>(ofs));
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值