Prettier search, tests

This commit is contained in:
Imbus 2024-12-05 12:32:27 +01:00
parent 1dae994364
commit 2769a3a0ad
2 changed files with 37 additions and 22 deletions

View file

@ -68,14 +68,12 @@ User UserTable::find(int c) const {
return found ? users[mid] : user_not_found;
}
User UserTable::find(std::string name) const {
for (int i = 0; i != n; ++i) {
if (users[i].getName() == name) {
return users[i];
} else {
return user_not_found;
}
}
return user_not_found;
auto it = std::find_if(users, users + n, [&name](const User &u) {
return u.getName() == name;
});
// If it is at the 'end' of users, the result is not found
return (it != users+n) ? *it : user_not_found;
}
void UserTable::ensureCapacity(int s) {

View file

@ -3,23 +3,40 @@
#include <cassert>
int main() {
// Two identical users
User u1 = User(1234, "Name Nameson");
User u2 = User(1234, "Name Nameson");
{ /* User Related Tests */
// Two identical users
User u1 = User(1234, "Name Nameson");
User u2 = User(1234, "Name Nameson");
assert(u1.getName() == u2.getName());
assert(u1.getCardNbr() == u2.getCardNbr());
assert(u1.getName() == u2.getName());
assert(u1.getCardNbr() == u2.getCardNbr());
// Two different users
User u3 = User(1200, "Name Surname");
User u4 = User(1201, "Name Nameson");
// Two different users
User u3 = User(1200, "Name Surname");
User u4 = User(1201, "Name Nameson");
assert(u3.getName() != u4.getName());
assert(u3.getCardNbr() != u4.getCardNbr());
assert(u3.getName() != u4.getName());
assert(u3.getCardNbr() != u4.getCardNbr());
}
{ /* Table Related Tests */
UserTable tbl1 = UserTable();
assert(tbl1.find("Jens Holmgren") == UserTable::user_not_found);
tbl1.addUser(User(1200, "Table Yes"));
assert(tbl1.getNbrUsers() == 1);
}
{
// Assumes 'users.txt' is present, containing
// line separated records formatted as:
// "89524 Adam Abrahamsson"
UserTable tbl = UserTable("users.txt");
assert(tbl.getNbrUsers() > 0);
assert(tbl.find("Jens Holmgren") != UserTable::user_not_found);
UserTable ut1 = UserTable("users.txt");
tbl.addUser(User(1200, "Name Surname"));
User ufind1 = tbl.find(1200);
assert(ufind1 != UserTable::user_not_found);
ut1.addUser(u3);
User us = ut1.find(1200);
assert(us != UserTable::user_not_found);
User ufind2 = tbl.find("Name Surname");
assert(ufind2 != UserTable::user_not_found);
}
}