在 std 列表中查找对象并将其添加到另一个列表

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

本文关键字:列表 添加 另一个 对象 std 查找      更新时间:2023-10-16

我正在尝试创建一个书店管理系统,该系统将允许我将以前创建的作者添加到数据库中,创建书籍,然后将作者分配给数据库中的书籍(这是一个std::list)。FindAdd 函数应该遍历数据库中的作者列表,并在其中找到给定的对象(临时作者),然后将此对象添加到书籍的作者列表中。

正在尝试将迭代器转换为对象,以便能够添加作者,但是这一行不允许我编译该程序(没有匹配的函数可以调用Book::AddAuthor(Author*))。我尝试过没有铸造,但当然它不起作用。我该如何解决这个问题?或者也许有一种更简单的方法来完成我在这里尝试做的事情?

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 只需要一个Book引用,所以你不需要做任何花哨的事情:

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";
}