How to write vector values to a file

前端 未结 4 750
闹比i
闹比i 2020-12-23 17:13

I have a large vector.

The ways that I use multiply the run-time of the program hugely. The first is write all values to a string as they are calculated using

相关标签:
4条回答
  • 2020-12-23 17:42

    You can use std::copy and std::ostream_iterator.

    0 讨论(0)
  • 2020-12-23 17:47

    Assuming you have C++11:

    #include <fstream>
    #include <vector>
    #include <string>
    
    int main()
    {
        std::vector<std::string> v{ "one", "two", "three" };
        std::ofstream outFile("my_file.txt");
        // the important part
        for (const auto &e : v) outFile << e << "\n";
    }
    
    0 讨论(0)
  • 2020-12-23 18:02

    Using std::ofstream, std::ostream_iterator and std::copy() is the usual way to do this. Here is an example with std::strings using C++98 syntax (the question was asked pre-C++11):

    #include <fstream>
    #include <iterator>
    #include <string>
    #include <vector>
    
    int main()
    {
        std::vector<std::string> example;
        example.push_back("this");
        example.push_back("is");
        example.push_back("a");
        example.push_back("test");
    
        std::ofstream output_file("./example.txt");
        std::ostream_iterator<std::string> output_iterator(output_file, "\n");
        std::copy(example.begin(), example.end(), output_iterator);
    }
    
    0 讨论(0)
  • 2020-12-23 18:02

    Maybe I have missed something, but what is wrong with:

    std::ofstream f("somefile.txt");
    for(vector<X>::const_iterator i = v.begin(); i != v.end(); ++i) {
        f << *i << '\n';
    }
    

    That avoids having to do potentially quadratic string concatenation, which I assume is what's killing your run-time.

    0 讨论(0)
提交回复
热议问题