The reason is pretty simple. When you use std::find
, what happens under the hood is something like this,
for(iterator i = begin; i != end; i++)
if(*i == check) return i;
Looking at this, you can see that when we pass in your list, the iterator type is std::list<accounts>::iterator
but what you check against is accounts::id
. There isn't a way to do this.
So what are the options? You have 3,
- Create a
==
operator to the accounts
struct.
- Just pass in
test
to test.
- Pass in a function to do the compare.
The first is simple, you can copy paste this if you want,
struct accounts {
long id;
int bal;
bool operator==(const long& otherID) const { return id == otherID; }
};
Now when std::find
calls the ==
operator, it knows what to do.
The third is simple, use a lambda.
check = find(accs.begin(), accs.end(), [&test](const accounts& other) {
return other.id == test.id; });
if (check == accs.end()) {
accs.push_back(test);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…