在 std 列表中查找对象并将其添加到另一个列表
Finding an object in a std list and adding it to another list
我正在尝试创建一个书店管理系统,该系统将允许我将以前创建的作者添加到数据库中,创建书籍,然后将作者分配给数据库中的书籍(这是一个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";
}
相关文章:
- 如何在 sqlite3 中的表中添加整数列表
- 有什么方法可以将元素添加到列表中,如图所示?
- 测试驱动开发 c++:如何将对象添加到向量中,将歌曲添加到播放列表并对其进行测试
- 将新元素添加到列表中,并返回对该元素的引用?
- 可视化 如何将 CString 值列表添加到 MFC C++ 中的组合框中?
- 通过在带有 C++ 的列表中添加连续元素来计算新的整数列表
- CSUF EPP - 你有什么想法(在添加到链接列表末尾时遇到麻烦)
- 将集合的随机元素添加到列表中,然后将其从原始集合中移除
- 如何使用LLVM C++API向保留节点列表添加
- 是否可以使用OpenMP并行化一个列表,该列表可以在每次迭代中添加新元素
- 如何确保我的节点被添加到链接列表中
- 双链接列表添加元素不起作用,不知何故它总是保持为空
- 链接列表添加CPP
- 通过相邻顶点列表添加和减去图形中的边
- 向 C 样式可变参数列表添加额外的参数
- C ++ win 32,我想将项目列表添加到组合框中.我该怎么做
- 如何将QActions列表添加到QMenu并用单个插槽处理它们
- 将一个类的列表添加到另一个类
- 向列表添加项和迭代器问题
- C++向列表添加新的指针对象