Hi, I have a question about vector.
Suppose that I have "vector<Object>" container, where Object is some class.
I would like to output this vector<Object> into a file to save. Then, in the
next time, I can re-load this data if necessary.
Could someone provide me some info?
Thanks.
There is no built in way to do what you want, you will need to write
things yourself. There is some help in the FAQ,
http://www.parashift.com/c++-faq-lite/, search for "serialization".
To get you started here is part of one possible solution:
rossum
----------------------------------
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cstdlib>
using std::string;
using std::vector;
using std:
stream;
using std:
fstream;
//-------------------------------------
class My_Object {
private:
int m_int;
string m_string;
double m_double;
public:
My_Object (int i, const string& s, double d) :
m_int(i), m_string(s), m_double(d) {}
friend ostream& operator<<(ostream& os, const My_Object& obj);
}; // end class my_Object
//-------------------------------------
ostream& operator<<(ostream& os, const My_Object& obj) {
const char delimiter = '|';
os << obj.m_int << delimiter
<< obj.m_string << delimiter
<< obj.m_double << delimiter;
return os;
} // end operator<<()
//-------------------------------------
void save_restart_data(ofstream& ofs, const vector<My_Object>&
obj_vec) {
for (int i = 0; i < obj_vec.size(); ++i) {
ofs << obj_vec
<< '\n';
} // end for
return;
} // end save_restart_data()
//-------------------------------------
int main() {
const char* restart_file_name = "restart-data.txt";
vector<My_Object> obj_vec;
obj_vec.push_back(My_Object(1, "first", 1.1));
obj_vec.push_back(My_Object(2, "second", 2.2));
obj_vec.push_back(My_Object(3, "third", 3.3));
ofstream restart_file;
restart_file.open(restart_file_name);
if (!restart_file) {
std::cerr << "Unable to open "
<< restart_file_name << ".\n";
}
else {
save_restart_data(restart_file, obj_vec);
std::cout << "Restart data saved in "
<< restart_file_name << ".\n";
} // end if
system("pause");
return EXIT_SUCCESS;
} // end main()
//-------------------------------------