#include <iostream>
#include <stack>
#include <fstream>
#include <string>
using std::stack;
using std::string;
using std::ifstream, std::ofstream;
using std::ios_base;
using std::cout, std::endl;
template<typename T>
void save(const string &filename, stack<T> s) {
stack<T> temp;
while(!s.empty()) {
temp.push(s.top());
s.pop();
}
ofstream os(filename, ios_base::out | ios_base::binary);
size_t size = temp.size();
os.write((const char *)&size, sizeof(size));
while(!temp.empty()) {
os.write((const char *)&temp.top(), sizeof(temp.top()));
temp.pop();
}
}
template<typename T>
void load(const string &filename, stack<T> &s) {
ifstream is(filename, ios_base::in | ios_base::binary);
if(!is) return;
//s.clear();
s = stack<T>();
size_t size;
is.read((char *)&size, sizeof(size));
for(size_t i = 0; i < size; ++i) {
T value;
is.read((char *)&value, sizeof(value));
s.push(value);
}
}
int main() {
{
stack<size_t> sa;
for(size_t i = 3; i < 8; ++i) {
sa.push(i);
}
save("stack.dat", sa);
stack<size_t> sb;
load("stack.dat", sb);
cout << (sa == sb ? "true" : "false") << endl;
sa.push(1234);
cout << (sa == sb ? "true" : "false") << endl;
}
{
stack<double> sa;
for(size_t i = 3; i < 8; ++i) {
sa.push(i + 3.14);
}
save("stack.dat", sa);
stack<double> sb;
load("stack.dat", sb);
cout << (sa == sb ? "true" : "false") << endl;
sa.push(1234.4321);
cout << (sa == sb ? "true" : "false") << endl;
}
return 0;
}
|