2012-12-11 115 views
0

在我目前的項目,我有以下類型組:迭代一個組指針

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的一個實例包含一個作者,標題,Pages數量和一套該書通用的關鍵字。我有這樣的功能:

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。感謝迄今爲止的幫助。

+0

那麼我明白如何使用for循環遍歷該集合,但是對於我遍歷的每個實例,我不確定如何將該實例的關鍵字列表與關鍵字參數進行比較。 –

+0

要比較實例的關鍵字列表,請首先遍歷關鍵字列表。 –

+0

好吧,你還沒有提供任何代碼來處理'Item',我猜是關鍵字存儲的地方。另外你應該使用'std :: unique_ptr'而不是'ItemPtr'。只要檢查關鍵字,它只是檢查關鍵字列表中的每個關鍵字.. –

回答

1

在簡單迭代而言,有幾種方法可以做到這一點:

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的代碼以及您自己的一些嘗試。

0

使用std ::設爲::找到檢查關鍵字是否存在於集 http://www.cplusplus.com/reference/set/set/find/

注:在你的帖子,你是在談論在列表中找到的關鍵詞。這不是你正在使用的列表。你正在使用一套。

+0

對不起,我說的名單,因爲我的集被稱爲keywordsList。我明白,是的,我可以使用find,但參數是_kty,在我的情況下是指ItemPtr。我不確定如何使用該類型的參數來訪問keywordsList,並開始比較。 –

+0

這是你想要的 它 - > getPtr() - > keywordsList.find(關鍵字) – bibbsey

+0

是的,但然後我會如何:A)比較它的參數,然後將該實例添加到我的臨時ItemSet,或B )如果該實例包含該關鍵字,則將該實例存儲到臨時ItemSet中?感謝您的幫助btw –