我在通过对象向量迭代时遇到问题。
在这个成员函数中,我试图逐步遍历数组的每个元素。 但是,尽管满足条件,但if语句似乎被跳过。 当我在函数开始时测试listAccounts.size()时,它会打印0。
void Account::change_balance(string name, int balance) {
for(auto& account : listAccounts) {
if(account.account_name == name) {
account.account_balance += balance;
cout << account.account_balance;
return;
}
}
cout << "account does not exist""\n";
}
因此我必须回到矢量listAccounts这是一个问题吗? 这是我推回向量的函数:
void Account::init_account(string name, char type) {
Account account;
if (type == 'y') {
account.account_type = 1;
} else if (type == 'n') {
account.account_type = 0;
}
account.account_name = name;
account.account_balance = 0;
listAccounts.push_back(account);
cout << listAccounts.size() << "\n";
}
每次用户在main中输入“create”时,都会调用相同的函数。 每次用户在main中输入'transaction'时都会调用change_balance函数。
这是类定义:
class Account {
public:
string account_name;
bool account_type;
int account_balance;
static vector<Account> listAccounts;
//member function declaration
void init_account(string name, char type);
void change_balance(string name, int balance);
void remove_account(string name);
};
vector<Account> Account::listAccounts;
该计划应创建一个名称为&amp;的帐户。类型,并回滚到listAccounts,以及在listAccounts中使用account_name = name更新vector元素的余额。
#include <iostream>
using namespace std;
#include <sstream>
#include <vector>
#include <algorithm>
class Account {
public:
string account_name;
bool account_type;
int account_balance;
static vector<Account> listAccounts;
//member function declaration
void init_account(string name, char type);
void change_balance(string name, int balance);
void remove_account(string name);
};
vector<Account> Account::listAccounts;
//member functions definitions
void Account::init_account(string name, char type) {
Account account;
cout << listAccounts.size(); //test to see size before pushback
if (type == 'y') {
account.account_type = 1;
} else if (type == 'n') {
account.account_type = 0;
}
account.account_name = name;
account.account_balance = 0;
listAccounts.push_back(account);
cout << "\n" << listAccounts.size() << "\n"; //test to see size
}
void Account::change_balance(string name, int balance) {
cout << listAccounts.size() << " accounts to check\n";
for(auto& account : listAccounts) {
cout << "Testing " << account.account_name << "\n";
if(account.account_name == name) {
account.account_balance += balance;
cout << account.account_balance;
return;
}
}
cout << "account does not exist""\n";
}
void Account::remove_account(string name) {
auto iter = std::find_if(listAccounts.begin(), listAccounts.end(),
[&](const auto& s){ return s.account_name == name; });
if(iter != listAccounts.end())
listAccounts.erase(iter);
}
//main
int main() {
char action;
string names;
char types;
int balance;
Account account;
while(action != 'q') {
int i = 0;
cin >> action >> names;
if (action == 'c') {
cin >> types;
account.init_account(names, types);
i++;
}
else if (action == 't') {
cin >> balance;
account.change_balance(names, balance);
}
else if (action == 'r'); {
account.remove_account(names);
}
return 0;
}