c – 使用迭代器正确读取和写入std :: vector到文件中

c – 使用迭代器正确读取和写入std :: vector到文件中,第1张

概述我试图理解 here提供的答案,但我似乎无法使其发挥作用. 这是我尝试过的: #include <algorithm>#include <iostream>#include <iterator>#include <vector>#include <fstream>int main(){ std::string path("numbersfile"); std::ve 我试图理解 here提供的答案,但我似乎无法使其发挥作用.

这是我尝试过的:

#include <algorithm>#include <iostream>#include <iterator>#include <vector>#include <fstream>int main(){    std::string path("numbersfile");    std::vector<int> myVector{1,16,32,64};    std::vector<int> newVector{};    std::ofstream file(path,std::ios::out | std::ofstream::binary);    std::copy(myVector.begin(),myVector.end(),std::ostreambuf_iterator<char>(file));    std::ifstream INfile(path,std::ios::in | std::ifstream::binary);    std::istreambuf_iterator<char> iter(INfile);    //std::copy(iter.begin(),iter.end(),std::back_inserter(newVector)); //this doesn't compile    std::copy(iter,std::istreambuf_iterator<char>{},std::back_inserter(newVector)); // this leaves newVector empty}

最后一次复制后,newVector仍为空.如何更新最后一个语句以填充newVector?

解决方法 在调用第二个副本时,文件尚未准备好读取. (感谢Piotr Skotnicki在评论中的回答)

拨打flush可以使程序正常工作:

#include <algorithm>#include <iostream>#include <iterator>#include <vector>#include <fstream>int main(){    std::string path("numbersfile");    std::vector<int> myVector{1,std::ostreambuf_iterator<char>(file));    file.flush(); // required here    std::ifstream INfile(path,std::back_inserter(newVector)); // this leaves newVector empty    return 0;}

创建ifstream时,ofstream仍在范围内.如果已经调用了ofstream的析构函数,那么该文件也已经为ifstream做好了准备.在以下程序中,ifstream会自动销毁:

#include <algorithm>#include <fstream>#include <iterator>#include <vector>std::string filename("numbersfile");std::vector<double> myVector{1.342,16.33,32.1,12364};voID write_vector_to_file(const std::vector<double>& myVector,std::string filename);std::vector<double> read_vector_from_file(std::string filename);int main(){    write_vector_to_file(myVector,filename);    auto newVector{read_vector_from_file(filename)};    return 0;}voID write_vector_to_file(const std::vector<double>& myVector,std::string filename){    std::ofstream ofs(filename,std::ios::out | std::ofstream::binary);    std::ostream_iterator<double> osi{ofs," "};    std::copy(myVector.begin(),osi);}std::vector<double> read_vector_from_file(std::string filename){    std::vector<double> newVector{};    std::ifstream ifs(filename,std::ios::in | std::ifstream::binary);    std::istream_iterator<double> iter{ifs};    std::istream_iterator<double> end{};    std::copy(iter,end,std::back_inserter(newVector));    return newVector;}
总结

以上是内存溢出为你收集整理的c – 使用迭代器正确读取和写入std :: vector到文件中全部内容,希望文章能够帮你解决c – 使用迭代器正确读取和写入std :: vector到文件中所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1221440.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-05
下一篇2022-06-05

发表评论

登录后才能评论

评论列表(0条)

    保存