2016-06-21 7 views
0

まずは愚かな質問があれば申し訳ありませんが、私はC++の初心者です。マルチマップの要素が値がC++の場合のみ

私はライブラリを表すシステムを書いており、私たちが本を取り除くことができるようになっている私のライブラリクラスのメンバ関数があります。今、本がユーザーによって貸与されている場合は、私の_usersLoaningMultimapmultimap<UserId,LoanInfo>)に要素があることを意味します。キー(UserId)を知らなくても、私が望むLoanInfoを見つける方法はありますか?

bool Library::removeBook(const BookId& bookId){ 
//how to find my book in my library without knowing who loaned it. 

}

ちょうどそれをより明確にするために、私のクラスライブラリは、そのようなものです:

class Library { 
public: 
Library(); 
void addUser(const UserId&, const string&); 
Optional<string>& getUserInfo(const UserId& userId); 
void addBook(const BookId& bookId, const string& description); 
Optional<string>& getBookInfo(const BookId& bookId); 
bool returnBook(const UserId& userId, const BookId& bookId); 
void loanBook(const UserId& userId,LoanInfo& loan); 
bool removeUser(const UserId& userId); 
void getLoansSortedByDate(const UserId,std::vector<LoanInfo>& loanVector); 

~Library() {} 
private: 
map<BookId, string> _bookMap; 
map<UserId, string> _userMap; 
multimap<UserId, LoanInfo> _usersLoaningMultimap; 

}; 

答えて

0

あなたが全体を反復処理する必要があります

for(multimap<userId,LoanInfo>::iterator it = _usersLoaningMultimap, it != _usersLoaningMultimap.end(); it++){ 
    //it->first retrieves key and it->second retrieves value 
    if(it->second == loan_info_you_are_searching){ 
     //do whatever 
    } 
} 
+0

ありがとうございます! – adlsc

0

std::multimapは、値のルックアップのための任意の方法を提供していません。あなたの唯一の選択は、特定の価値を探すマルチマップを読むことです。

あなたはその目的のためにstd::find_ifを使用することができます。

using const_ref = std::multimap<UserId, LoanInfo>::const_reference; 
std::find_if(_usersLoaningMultimap.begin(), _usersLoaningMultimap.end(), 
    [&](const_ref a) -> bool { 
     return a.second == your_loan_info; 
    }); 

あなたは構文が気に入らない場合、あなたはまた、独自の機能を行うことができます。

using Map = std::multimap<UserId, LoanInfo>; 
auto findLoanInfo(const Map& map, const LoanInfo& info) -> Map::iterator { 
    for (auto it = map.begin(); it != map.end(); ++it) { 
     if (it->second == info) { 
      return it; 
     } 
    } 

    return map.end(); 
} 
+0

@adlsc最初の編集がうまくいきませんでした。もう一度この回答を読むことをおすすめします。あなたが何かを理解していない場合は、正確に指摘してください。 – Nelfeal

関連する問題