检查值是否属于某个对象

时间:2016-06-29 10:36:01

标签: c++ dictionary key equality

我有一张包含两种不同物品的地图:存款帐户和支票帐户。我想写一个汇款方法,只在两个支票账户之间转账。有没有办法检查两个帐号是否属于同一个支票帐户对象?

bool Bank::moneyTransfer(long fromAccount,long toAccount, double amount)
{
    map<long, account*>::iterator iterFrom;
    map<long, account*>::iterator iterTo;

    iterFrom = m_accountList.find(fromAccount);
    if (iterFrom == m_accountList.end()) {
        return false;
    }
    iterTo = m_account.find(toAccount);
    if (iterFrom == m_accountList.end()) {
        return false;
    }

    Konto *fromAccount = iterFrom->second;
    Konto *toAccount = iterTo->second;

    if (!fromAccount->drawMoney(amount)) {
        return false;
    }
    toAccount->payIn(amount);

    return true;
}  

1 个答案:

答案 0 :(得分:0)

Q值。有没有办法检查两个帐号是否属于同一个支票帐户对象?

甲。是

正如Shaktal says那样,您只需比较一下帐号即可。

您的代码中需要清理几件事情:

  1. 您提出此问题的事实表明,您认为map中有2个值可以使用相同的密钥。情况并非如此,此代码将导致Key 13映射到 a DepositAccount
  2. m_accountList[13] = CheckingAccount();
    m_accountList[13] = DepositAccount();
    
    1. 请使用auto声明您的变量,特别是代替map<long, account*>::iterator,除了更容易阅读之外,您不必在更改m_accountList时更改回来编辑逻辑39; s类型,有关auto的更多信息,我相信最终文章是:https://herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/
    2. 进行这些更正后,您的代码应如下所示:

      bool Bank::moneyTransfer(long fromAccount, long toAccount, double amount)
      {
          if(fromAccount != toAccount) {
               auto iterFrom = m_accountList.find(fromAccount);
      
              if (iterFrom != m_accountList.end()) {
                  auto iterTo = m_account.find(toAccount);
      
                  if (iterFrom != m_accountList.end() && iterFrom->second->drawMoney(amount)) {
                      iterTo->second->payIn(amount);
      
                      return true;
                  }
              }
          }
          return false;
      }