-
reading deque from file
I was trying to write a pretty simple class to a binary file. The class includes a couple integers, some other stuff and a deque. All went well writing and reading the data, but when I added elements to the deque I got a dialog box that said:
"Debug Assertion Failed!"
This only seems to happen as the program is exiting because when I set a breakpoint right before it exited, the program ran fine up to it and all the data seems intact. I am completly stumped on this and I couldn't find anything that helped online. Does anyone know what the error means or anything I can do to fix it?
-
Assertion failure isnt a specific error, it can be anything.
Assertions is used to detect unvalid variable content.
void add_to_list(Object *a)
{
// Make sure the object isnt NULL
ASSERT(a != NULL);
list.add(a);
}
When add_to_list is called with a NULL pointer the program halts. A "Debug assertion failure" has occured.
Paste some code, its easier to help then =)
-
ok, this is a simplified version that has the exact same problem. I included the whole program, which compiles in Visual C++.
Code:
#include <deque>
#include <iostream>
#include <fstream>
class MyClass //This is the class
{
std::deque<int> MyDeque;
public:
void AddElement(int e){ //Function to add an element to the deque
MyDeque.push_back(e); }
};
bool Save(MyClass *, char *); //Save
bool Load(MyClass *, char *); //Load
int main()
{
MyClass NewClass;
NewClass.AddElement(10); //Add 10 to the deque
Save(&NewClass, "file.txt");//Save this class
MyClass AnotherClass;
Load(&AnotherClass, "file.txt");//Load the same information into a different class
//I Get the dialog box around here, right after the class is loaded
return 0;
}
bool Save(MyClass * cl, char * file) //Function to save the class in binary mode
{
if (file==NULL) return false;
std::ofstream fout(file, std::ios_base::out | std::ios_base::binary | std::ios_base::trunc);
if (!fout.is_open())
return false;
else
fout.write((const char*)cl, sizeof(MyClass));
fout.close();
return true;
}
bool Load(MyClass * cl, char * file) //Function to load the class
{
if (file==NULL) return false;
std::ifstream fin(file, std::ios_base::in | std::ios_base::binary);
if (!fin.is_open())
return false;
else
fin.read((char *)cl, sizeof(MyClass));
fin.close();
return true;
}
I tried this with a vector instead of a deque and it had the same problem(I don't know why the result would be different because they are so similar but it was worth a shot...)
-
Sorry, but i dont think you can save a stl class like that. You have to iterate the deque and save every item.
The class probably contains pointers, and thoose can be saved.