music lml
music lml

Reputation: 13

I have a problem with a program for a library

I have a class that is creating books, and also a class where it is going to save the books in an array, but I have to make a method that prints all the books that have the same title but of a different year, and it happens to me that this failing from code what it does is that it duplicates some books, is there a way to prevent this from happening to me?

void buscarNombre(string elemento){
            int i, j;
            int largo = 0;
            bool primeraVez = true;
            largo=contadorLibros();
            
            for(i=0;i<largo-1;i++){
                if (vec[i].getTitulo() == elemento){
                    for(j=i+1;j<largo;j++){
                        if (vec[j].getTitulo() == elemento){
                            if(vec[i].getAnnioImpresion() != vec[j].getAnnioImpresion()){
                                if(primeraVez == true){
                                    cout<<vec[i].toString()<<endl;
                                    primeraVez = false;
                                    
                                }
                                else{
                                    cout<<vec[j].toString()<<endl;
                                }
                                
                            }
                        }
                    }
                    primeraVez = true;
                }
            }
        }

Upvotes: 0

Views: 107

Answers (2)

Abhist
Abhist

Reputation: 43

Is it printing the books having same title and are of same year? And why you have the if condition where you are printing the title maybe 'cout' inside else condition is causing that duplicacy.

Upvotes: 0

haytaylan
haytaylan

Reputation: 64

I dont know your native language but if I understand the code correctly:

Assume you have three books with the same title but different publishing dates, lets call the books A,B,C.

When you encounter A in the first loop, you start looping the second loop. When you encounter B, you set primeraVez = false to prevent printing again when you encounter C; however after the second loop completes, you reset primeraVez = true, so when you encounter B in the first loop, you reprint the book name in the second loop when you encounter C.

You can prevent this by deleting the books you print out from the list or make a std::set of books you want to print out and print after the searching completes.

Upvotes: 1

Related Questions