I want to sort my FirstName data member into alphabetical order using the STL sort algorithm and then print to screen. How would I go about doing this?
The commented out case 's' creates an error but i'm not even sure how to access the name member because if you use just Name.begin() what is it actually sorting, name or pnum?Code:#include <iostream> #include <string> #include <fstream> #include <vector> #include <algorithm> using namespace std; class Person { private: string FirstName; string PhoneNumber; public: Person(const char *name,const char *number): FirstName(name), PhoneNumber(number) { } void FilePerson(); friend ostream& operator<<(ostream& os,const Person& p); }; void Person::FilePerson() { ofstream myfile; myfile.open("Person.txt" , ios::app); myfile << FirstName << ":" << PhoneNumber << endl; myfile.close(); } ostream& operator << (ostream& os,const Person& p) { return(os<<"First Name:"<<p.FirstName<<endl<<"Phone Number:"<<p.PhoneNumber<<endl); } int main(int argc,char *argv[]) { char nresponse; char name[20]; char pnum[20]; int i = 0; vector<Person> Name; vector<Person>::const_iterator pos; do { cout << "***********************PERSON DATABASE PROGRAM**************************" << endl; cout << " Enter any of the following commands:" << endl; cout << " Enter n to enter a new person into database " << endl; cout << " Enter p to print details to screen " << endl; cout << " Enter f to print details to file " << endl; cout << " Enter s to sort name into alphabetical order " << endl; cout << " Enter q to quit program\n" << endl; cin >> nresponse; switch (nresponse){ case 'n': cout << "Enter the first name: "; cin >> name; cout << "Enter a phone number: "; cin >> pnum; Name.push_back(Person(name,pnum)); break; case 'p': for(pos=Name.begin();pos!=Name.end();++pos){ cout << *pos << endl; } break; case 'f': for(i=0;i<Name.size();i++){ Name[i].FilePerson(); } break; //case 's': //sort(Name.begin(),Name.end()); //for(pos=Name.begin();pos!=Name.end();++pos){ // cout << *pos << endl; //} case 'q': Name.clear(); cout << "Exiting Person Database ... " << endl; break; default: cout << "Invalid Input" << endl; } }while (nresponse != 'q'); return 0; }
Any help would be great