gpt4 book ai didi

c++ - 遍历一组指针

转载 作者:行者123 更新时间:2023-11-28 07:50:53 24 4
gpt4 key购买 nike

在我当前的项目中,我有以下类型的集合:

typedef set<ItemPtr>            ItemSet;

ItemPtr 是这个类:

class ItemPtr
{
private:
Item *ptr;

public:
ItemPtr(Item *ptr) : ptr(ptr) { }
Item* getPtr() const { return ptr; }
};

以及以下集合:

ItemSet bookList;
ItemSet movieList;
ItemSet musicAlbumList;

所有集合都包含在一个名为 Library 的类中。这些集合中的每一个都包含 ItemPtr 的实例,其中 ItemPtr 的每个实例都包含一个指向 Book、Movie 或 MusicAlbum 实例的指针。其中每一个都是从名为 Item 的类派生的类。 Book 的一个实例,包含作者、标题、页数和一组该书常用的关键字。我有这样的功能:

const ItemSet* Library::itemsForKeyword(const string& keyword)
{
return NULL; //need to put code in here
}

需要返回每个集合中在其关键字列表中具有该参数的所有项目。我不确定如何遍历每个集合并访问它的关键字,然后将它们与上述函数的参数进行比较。我怎样才能做这样的比较?

这是我的项目类:

class Item
{
public:
string mTitle;
string mArtist;
Item(const string& title, const string& artist);
Item();
virtual ostream &print(std::ostream &os) const
{
os << "author: \t" << mArtist << endl;
os << "title: \t" << mTitle << endl;
return os;
}
virtual ~Item();
set<string> keywordsList;
void addKeywords(string keyword);
};

这是 addKeywords 函数:

void Item::addKeywords(string keyword)
{
keywordsList.insert(keyword);
}

这是到目前为止我编写我需要的函数的情况:

const ItemSet* Library::itemsForKeyword(const string& keyword)
{
ItemSet temp;

for(it=bookList.begin();it!=bookList.end();it++){
if(it->getPtr()->keywordsList)


}

return &temp;
}

我知道通过用我的迭代器引用 getPtr,它可以让我访问 keywordsList,但从那时起我不知道如何检查列表以将它与传入的关键字进行比较。我的计划是,在比较并找到匹配项之后,将实例存储在 temp 中,然后将包含该关键字的所有项目传回 temp。感谢迄今为止的帮助。

最佳答案

就简单迭代而言,有以下几种方法:

在 C++11 之前:

const ItemSet* item_set = // ...
for (ItemSet::const_iterator it = item_set->begin(); it != item_set->end(); ++it) {
const ItemPtr item = *it;
// ...
}

在 C++11 之后(使用自动):

const ItemSet* item_set = // ...
for (auto it = item_set->cbegin(); it != item_set->cend(); ++it) {
const ItemPtr item = *it;
}

在 C++11 之后(使用 ranged-for):

const ItemSet* item_set = // ...
for (auto item : *item_set) {
// ...
}

就处理每个项目而言,您需要先向我们展示 Item 的代码以及您自己的一些尝试。

关于c++ - 遍历一组指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13814210/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com