gpt4 book ai didi

c++ - 在 C++ 中搜索结构 vector 并输出元素

转载 作者:行者123 更新时间:2023-11-30 05:03:14 25 4
gpt4 key购买 nike

好吧,我的结构看起来像这样:

struct Account{
int accountNumber;
string lastName;
string firstName;
double accountBalance;
bool active;
};

我已经将帐户硬编码到其中,即

vector<Account> subAccount = *account;
Account newA;
newA.accountNumber = 2345;
newA.lastName = "test1";
newA.firstName = "test1";
newA.accountBalance = 100.00;
newA.active = true;

subAccount.push_back(newA);

还有第二个帐户:

Account newB;
newB.accountNumber = 1234;
newB.lastName = "test2";
newB.firstName = "test2";
newB.accountBalance = 178.1;
newB.active = true;

subAccount.push_back(newB);

*account = subAccount;

所以现在我需要能够在类型为 void 的函数中打印个人帐户。当提示用户输入帐号时,搜索 vector/结构的最佳方式是什么?我试过这样做:

for (int i = 0; i < subAccount.size(); i++){

if (TempActNum == subAccount[i].accountNumber) {
cout << "Account Number: " << subAccount[i].accountNumber << " Balance: " << subAccount[i].accountBalance
<< endl;
cout << "Last Name: " << subAccount[i].lastName << " First Name: " << subAccount[i].firstName << endl;
break;
}

if (TempActNum != subAccount[i].accountNumber) {
cout << "This account does not exist." << endl;
}

} }

此方法的问题是,如果我输入第二个帐号 (1234),它会打印“此帐户不存在”。以及所有帐户详细信息。那么什么是更好的搜索和打印方式呢?或者什么可以解决我的问题?感谢您的宝贵时间。

最佳答案

你的问题是 non existance 的测试在循环的中间。

for (int i = 0; i < subAccount.size(); i++){

if (TempActNum == subAccount[i].accountNumber) {
cout << "Account Number: "
<< subAccount[i].accountNumber
<< " Balance: "
<< subAccount[i].accountBalance
<< endl;
cout << "Last Name: "
<< subAccount[i].lastName
<< " First Name: "
<< subAccount[i].firstName
<< endl;
break;
}

if (TempActNum != subAccount[i].accountNumber) {
cout << "This account does not exist." << endl;
}

}

只有在遍历完所有账号后,才能判断是否没有找到账号。因此,创建一个临时变量来表示它已找到。

bool found = false;
for (int i = 0; i < subAccount.size(); i++){

if (TempActNum == subAccount[i].accountNumber) {
cout << "Account Number: "
<< subAccount[i].accountNumber
<< " Balance: "
<< subAccount[i].accountBalance
<< endl;
cout << "Last Name: "
<< subAccount[i].lastName
<< " First Name: "
<< subAccount[i].firstName
<< endl;
found == true; // You found it.
break;
}

}
// After you have checked all the accounts (or after breaking out)
// you can print this statement if it was not found.
if (!found) {
cout << "This account does not exist." << endl;
}

另请注意,我们可以简化您的帐户创建:

vector<Account> subAccount = {
{ 2345, "test1", "test1", 100.00, true},
{ 1234, "test2", "test2", 178.1, true}
};

关于c++ - 在 C++ 中搜索结构 vector 并输出元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49518694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com