I'm using VS2013 to work on this program. I'm not using OOP (I'm not coding any classes) so my objects are just structs.
There's a struct holding data about a book (name, genre and isbn of a book):
1 2 3 4 5 6
|
struct t_libro
{
string nombre;
string genero;
long isbn;
};
|
I read the necessary info from keyboard and store it in a text file. So far so good, that works.
Then I want to allow the user to delete a book from the file. So I first load all the file contents into a vector<libro> (which I've called "coleccion_libros"), and this also works ok.
I ask the user which book to delete, and allow them to search by name ("nombre_buscado"). I do the required changes (i.e.: delete a book) in the vector, which I finally serialize again into the text file, replacing the previous file contents.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
auto iterador = coleccion_libros.begin();
while (iterador != coleccion_libros.end())
if (iterador->nombre == nombre_buscado) //nombre_buscado holds the book name user is searching for
{
eliminar_libro(iterador, coleccion_libros);
}
else
++iterador;
if (iterador == coleccion_libros.end())
cout << "\n\n\***BOOK NOT FOUND***";
}
//Once the vector is modified, erase file contents so the new vector can be saved
ofstream archivo("libros.txt", ios::trunc);
archivo.close();
//Serialize vector contents into file
for (auto libro : coleccion_libros)
serializar_libro("libros.txt", libro);
|
This is my delete function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
void eliminar_libro(vector<t_libro>::iterator iterador, vector<t_libro>& libros)
{
char opcion;
do {
cout << "\n\nDO YOU WISH TO DELETE [" << iterador->nombre << "]? (Y)es/(N)o: ";
cin >> opcion;
cin.ignore();
tolower(opcion);
} while ((opcion != 'y') && (opcion != 'n'));
if (opcion == 'y'){
cout << "\n\n[ " << iterador->nombre << " ] ";
iterador = libros.erase(iterador);
cout << "***BOOK WAS REMOVED***";
}
else
cout << "\n***NO DATA HAS BEEN ALTERED***";
}
|
I have a similar function to modify data, in which I pass the iterator as an argument in the same way as in the delete function. The modify function works perfectly.
But when it comes to deleting, I get a "vectors iterator incompatible" error:
http://k46.kn3.net/8/8/2/3/D/6/D7A.jpg
This error is thrown right after the console outputs "***BOOK WAS REMOVED***".
I've read a few other threads about this but I don't see anything in common with my code so I'm a bit clueless on what could be going on.
Is this a Visual Studio bug, as I've read somewhere? If not, what am I doing wrong?
Thanks!!