How to return null in map?

Viewed 538

I am trying to return null if the accountNo wasn't find the the map. But I have only used linkedlist in the past in java. I have no idea how to return something else in c++ map.

113 Account Bank::BalanceEnquiry(long accountNo){
114         map<long, Account>::iterator itr = accounts.find(accountNo);
115         return itr->second;
116 }       

Can anyone help?

2 Answers

You can use std::optional, which is a wrapper that may or may not contain a value:

std::optional<Account> Bank::BalanceEnquiry(long accountNo){
    auto itr = accounts.find(accountNo);
    
    if(itr == accounts.end()) {
        return std::nullopt; // empty value, that's like null from Java
    }

    return std::optional<Account>{itr->second}; // return non-empty value
}  

It can be used like this (with a Bank-object myBank):

std::optional<Account> balanceEnquiry = myBank.BalanceEnquiry(someValue);

if(balanceEnquiry) {
    // entry found, we can extract the actual value

    Account foundAccount = balanceEnquiry.value();
}
else {
    // entry not found
}

Unlike Java in C++ you can return object by value (or by reference) or by pointer. If you are returning by value (as in your code) you cannot return nullptr unless your class Account has special state. So you have to change return type. Possible variants:

// return a pointer
Account *Bank::BalanceEnquiry(long accountNo){
      auto itr = accounts.find(accountNo);
      return itr == accounts.end() ? nullptr : &(itr->second);
}
// usage
auto account = bank.BalanceEnquiry(123);
if( account ) account->do_something();

// return std::optional
std::optional<Account> Bank::BalanceEnquiry(long accountNo){
      auto itr = accounts.find(accountNo);
      return itr == accounts.end() ? std::optional<Account>() : itr->second;
}
// usage
auto account = bank.BalanceEnquiry(123);
if( account ) account.value().do_something();
Related