If you have no restriction as to what you are allowed to use, I highly recommend you use the class "set" (#include <set>) 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(); …