Search code examples
c++findmultimap

finding an element in a multimap ONLY with its value c++


First of all sorry if I am asking stupid questions, but I am a beginer in c++.

I am writing a system that represents a library and there is a member function of my Library class that is supposed to allow us to remove a book. Now, if the book is loaned by a user, means there is an element in my _usersLoaningMultimap (multimap<UserId,LoanInfo>). How can I find the LoanInfo that I want without knowing the key (UserId)?

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

}

Just to make it clearer, my class Library is like that:

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;

};

Solution

  • You have to iterate through the whole map like this :

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