Exercise: Search a User By Lastname#
Description#
The original C implementation (download userdb.h, download userdb.cpp to search a user is by equality of her
lastname:
struct User* userdb_search_by_lastname(struct UserDB*, char lastname[]);
As always, in C this can be done better: in class UserDB,
implement a method
class UserDB
{
public:
...
User search_by_lastname(const std::string& lastname) const;
...
};
search_by_lastname() returns the first user whose lastname is
lastname. If there are multiple users with that name, the rest
goes undetected.
Test this using the following program (feel free to use your own version of it):
#include "userdb.h"
#include <iostream>
#include <cassert>
int main()
{
UserDB db;
// setup db to have something to search for
// ----------------------------------------
db.insert(User("Philipp", "Lichtenberger", 35));
db.insert(User("Joerg", "Faschingbauer", 55));
db.insert(User("Caro", "Faschingbauer", 24));
// test the search
// ---------------
// we find the *first* user if it exists
User found = db.search_by_lastname("Faschingbauer");
assert(found.firstname() == "Joerg");
assert(found.lastname() == "Faschingbauer");
assert(found.age() == 55);
// lacking knowledge of exception handling, we have to return an
// invalid user when none exists.
User notfound = db.search_by_lastname("DoesNotExist");
assert(!notfound.isvalid());
return 0;
}