简体   繁体   中英

Finding an object in a std list and adding it to another list

I'm trying to create a bookshop management system that will allow me to add previously created authors to a database, create books and then assign an author to a book from the database (which is a std::list). The FindAdd function is supposed to iterate over a list of authors in the database and find a given object (temporary author) in it and then add this object to a book's authors list.

I'm trying to cast the iterator to an object so I'm able to add the author, but this line won't allow me to compile this program (no matching function to call for to Book::AddAuthor(Author*)). I tried it without casting, but of course it won't work. How can I fix this? Or maybe there's an easier method to accomplish what I'm trying to do here?

class Author
{
private:
    string name, lname;
public:
    bool operator==(const Author & a) const
    {
        bool test=false;
        if(!(this->name.compare(a.name) && this->lname.compare(a.lname)))
            test=true;
        return test;
    }
    Author(string namex, string lnamex)
    {
        name=namex;
        lname = lnamex;
    }
};
class Book
{
public:
    list <Author> Authorzy;
    string tytul;

    void AddAuthor(Author & x)
    {
        Authorzy.push_back(x);
    }
    Book(string tytulx)
    {
        tytul = tytulx;
    }
};

class Database
{
    protected:
    list <Author> authors;
    public:
    void AddAuthor(Author x)
    {
    authors.push_back(x);
    }
    list <Author> getAuthors
    {
    return authors;
    }
};

void FindAdd(Author & x, Book &y, Database & db)
{
  list <Author>:: iterator xx;
        xx = find(db.getAuthors().begin(), db.getAuthors().end(), x);
        if (xx != db.getAuthors().end())
        y.AddAuthor(&*xx);
        else cout << "Author not found";
}

int main(){
Author testauthor("test", "test");
Database testdb;
testdb.AddAuthor(testauthor);
Book testbook("Mainbook");
FindAdd(Author notfound("Another", "Guy"), testbook, testdb);
FindAdd(testauthor, testbook, testdb);
}

AddAuthor Just takes a Book Reference, so you dont need to do anything fancy:

if (xx != db.getAuthors().end()) {
    y.AddAuthor(*xx); // Just dereference the iterator and pass it 
                      // in, c++ takes care of the rest
} else {
    cout << "Author not found";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM