对于循环迭代器问题 c++



我在让我的代码抛出运行时错误以及让这些循环正常工作时遇到了问题,我不确定为什么。

如果用户要输入名称和余额,例如:josh 100,则程序应在 listAccounts 向量中名为 josh 的帐户中添加 100,然后打印新的余额。

关于这一行的东西: for ( ; iter != listAccounts.end(); iter++) {

由于某种原因,它导致 if 语句不起作用,如果我注释掉该行,该函数可以工作,但仅适用于 listAccounts 中的最后一个元素。for 循环是否有问题导致它无法单步执行每个元素?

void Account::change_balance(string name, int balance, int i) {
    try {
        auto iter = listAccounts.begin();
        for ( ; iter !=  listAccounts.end(); iter++) {
            if ((*iter).account_name == name) {
                if (((*iter).account_type == 0) && (((*iter).account_balance + 
                balance) < 0)) {
                    throw runtime_error("account cannot hold negative 
                    balance");                    
                    (*iter).account_balance = (((*iter).account_balance) -
                    (balance));
                    cout << (*iter).account_balance;                                                
                } else {                                                                            
                    (*iter).account_balance = balance + 
                    (*iter).account_balance;
                    cout << (*iter).account_balance;
                }
            }
        }
    }
    catch (runtime_error& e) {         
        cout << "error on line " << i << ": " << e.what() << "n"; 
    }
}

我不知道我哪里出错了,任何迹象将不胜感激。谢谢。

检查你内心的 for 循环。你永远不会增加迭代器,你所做的只是将 listAccounts.size() 乘以向量的相同元素与函数参数进行比较。由于循环在 k == listAccounts.size() 时结束,因此条件 n == listAccounts.size() 只有在外部循环至少运行一次时才能满足,因为您没有清除 n(或在本地定义它)。但是现在,它可能会触发并说"找不到帐户",即使它在那里,因为n == listAccounts.size()。这不是您想要的行为。

你应该重新考虑你的算法。为什么每次遍历帐户列表时都要遍历所有帐户?做一次就完全够了。考虑执行以下操作:

for(auto& account : listAccounts) {
   if(account.account_name == name) {
      // do your logic stuff and eventually:
      return;
   }
}
// if your program gets here, no account with such a name was found

最新更新