If you have no restriction as to what you are allowed to use, I highly recommend you use the class " set " (#include ) to store the records. In order to use it, you will need to overload the less-than operator (<) in whichever way you like to sort the elements. A simplified version of your problem would look like this:
#include <set>
#include <string>
#include <iostream>
class PhoneRecord {
private:
std::string last_name;
std::string first_name;
std::string phone_number;
public:
PhoneRecord(const std::string& aLastName = "",const std::string& aFirstName = "",const std::string& aPhoneNumber = "") : last_name(aLastName), first_name(aFirstName), phone_number(aPhoneNumber) { };
~PhoneRecord() { };
PhoneRecord(const PhoneRecord& aObj) : last_name(aObj.last_name), first_name(aObj.first_name), phone_number(aObj.phone_number) { };
PhoneRecord& operator=(const PhoneRecord& aObj) {
last_name = aObj.last_name;
first_name = aObj.first_name;
phone_number = aObj.phone_number;
return *this;
};
//this is the overloaded operators you need for having an ordered set:
bool operator <(const PhoneRecord& aObj) const {
if(last_name < aObj.last_name)
return true;
else if(last_name == aObj.last_name)
return (first_name < aObj.first_name);
else
return false;
};
bool operator ==(const PhoneRecord& aObj) const {
return ((last_name == aObj.last_name) && (first_name == aObj.first_name));
};
//to be able to print, you need the following friend operator:
friend std::ostream& operator<<(std::ostream& out, const PhoneRecord& aObj);
};
std::ostream& operator<<(std::ostream& out, const PhoneRecord& aObj) {
return out << "Name: " << aObj.last_name << ", " << aObj.first_name << "\t Phone Number: " << aObj.phone_number;
};
int main() {
std::set<PhoneRecord> phone_book;
//add a bunch of records, in random order:
phone_book.insert(PhoneRecord("Smith","James","555-7624"));
phone_book.insert(PhoneRecord("Doe","John","555-3424"));
phone_book.insert(PhoneRecord("Doe","Jane","555-9803"));
//print the list out:
std::set<PhoneRecord>::iterator it = phone_book.begin();
std::cout << "The phone book is now:" << std::endl;
for(;it != phone_book.end();++it)
std::cout << (*it) << std::endl;
//find a particular entry by name:
std::cout << "Now looking for John Doe..." << std::endl;
it = phone_book.find(PhoneRecord("Doe","John")); //notice no need for phone number.
if(it != phone_book.end())
std::cout << "Found: " << (*it) << std::endl;
else
std::cout << "Could not find John Doe!" << std::endl;
return 0;
};
If you cannot use the C++ standard implementation of a set or map, you should mimic their design, it is the best model you could find.
N.B.: For those who might critique that I gave too much away in this post, note that I have no more here than what is found on the reference pages on the "set" class, for which the link is provided.
mike_2000_17
Posting Virtuoso
Moderator
2,134 posts since Jul 2010
Reputation Points: 1,634
Solved Threads: 457