我的数据结构是:
vector <pair <int, vector <SavingsAccount*>>> accVec;
其中int
是银行帐号。
我的目标是检查用户输入的帐号是否与int
向量中任何对中的任何accVec
相匹配。
主要,我正在使用类似的东西:
do {
iter = find_if (accVec.begin(), accVec.end(), findAccID);
if (iter == accVec.end()) {
cout << endl << "ERROR: Account Does Not Exist. Try Again." << endl;
}
} while (iter == accVec.end());
功能:
bool findAccID(pair <int, vector <SavingsAccount*>> accPair) {
static int i = 0, accID;
if (i == 0) {
cout << endl << "Enter The Account Number In Which You Want To Deposit: ";
cin >> accID;
i++;
}
if (accID == accPair.first) {
return true;
}
return false;
}
我正在向用户询问函数内的帐号,因为我找不到从accID
传递main()
作为参数的方法。只要用户输入错误的帐号,我都希望重复该问题。
有什么建议吗?
答案 0 :(得分:2)
使用lambda作为std::find_if()
的谓词:
#include <algorithm>
#include <utility>
#include <vector>
#include <iostream>
using namespace std;
struct SavingsAccount{};
int main()
{
vector<pair<int, vector<SavingsAccount>>> accVec;
vector<pair<int, vector<SavingsAccount>>>::iterator iter;
do {
cout << "Enter The Account Number In Which You Want To Deposit: ";
int accID;
cin >> accID;
iter = find_if(accVec.begin(), accVec.end(),
[=](pair<int, vector<SavingsAccount>> const &accPair) {
return accPair.first == accID;
}
);
if (iter == accVec.end()) {
cout << endl << "ERROR: Account Does Not Exist. Try Again." << endl;
}
} while (iter == accVec.end());
}
或函子:
#include <algorithm>
#include <utility>
#include <vector>
#include <iostream>
using namespace std;
struct SavingsAccount{};
class AccountFinder
{
int accID;
public:
AccountFinder(int accID) : accID{ accID } {};
bool operator()(pair<int, vector<SavingsAccount>> const &accPair)
{
return accPair.first == accID;
}
};
int main()
{
vector<pair<int, vector<SavingsAccount>>> accVec;
vector<pair<int, vector<SavingsAccount>>>::iterator iter;
do {
cout << "Enter The Account Number In Which You Want To Deposit: ";
int accID;
cin >> accID;
iter = find_if(accVec.begin(), accVec.end(), AccountFinder(accID));
if (iter == accVec.end()) {
cout << endl << "ERROR: Account Does Not Exist. Try Again." << endl;
}
} while (iter == accVec.end());
}