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 stringstreams
and later write the string to a file. The other method is to make a long string after the fact and write that to the file. However, both of these are very slow.
Is there a way to just write the vector's values to the text file immediately with line breaks?
read((char*)&list2[0], size2 * sizeof(Vertex)); There is other stuff in the Vector data structure, so this will make your new vector get filled up with garbage. Solution: When you are writing your vector into a file, don't worry about the size your Vertex class, just directly write the entire vector into memory.
In the for loop, size of vector is calculated for the maximum number of iterations of loop and using at(), the elements are printed. for(int i=0; i < a. size(); i++) std::cout << a.at(i) << ' '; In the main() function, the elements of vector are passed to print them.
Using std::ofstream
, std::ostream_iterator
and std::copy()
is the usual way to do this. Here is an example with std::string
s 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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With