Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write vector values to a file

Tags:

c++

vector

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?

like image 316
TimeCoder Avatar asked Jun 20 '11 02:06

TimeCoder


People also ask

How do you read and write vectors to a file in C++?

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.

How do you vector output?

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.


1 Answers

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); } 
like image 62
Johnsyweb Avatar answered Oct 06 '22 23:10

Johnsyweb