-3

I want to sort a name list using std::sort. The problem is that I can only sort first name instead of firstname and last name together, the class I have create is like this:

class Name{
public:
Name(string first, string last):firstName(first), lastName(last){};

string getFirstName() const{
    return firstName;
};

string getLastName() const{
    return lastName;
}

private:
string firstName;
string lastName;
};

Once I get first name and last name I store them in the class Name, but I read them from a file, and the code is like this

file.open("namelist.txt");

vector<string> strvec;
while (!file.eof()){
    string firstName, lastName;
    file >> firstName;
    file >> lastName;
    Name n(firstName,lastName);
    strvec.push_back(firstName);

}

As you can see I store first Name in the vector, so I can sort using

sort(strvec.begin(),strvec.end());

But I only sort the first name instead of all together, the idea of using class is that i could sort them together, my idea is using vector<Name> strvec but I don't know how to add firstname and lastname together in the vector, does anyone have idea of doing it?

lbjx
  • 195
  • 1
  • 3
  • 12

1 Answers1

1

std::sort provides ways of plugging in your own ordering functions.

You need to provide either a functor to the sort function, or a less than operator for your name class:

struct Name_Compare {
    bool operator()(const Name& a, const Name& b) {
        return a.getFirstName() < b.getFirstName();
    }
}

std::sort(names.begin(), names.end(), Name_Compare());

OR:

bool operator<(const Name& a, const Name& b) {
    return a.getFirstName() < b.getFirstName();
}

std::sort(names.begin(), names.end());

Or, if you're compiling with C++11, you can do this all inline with a lambda:

std::vector<Name> names;

//Add your names...

std::sort(names.begin(), names.end(), 
          [](const Name& a, const Name& b) { 
              return a.getFirstName() < b.getFirstName()
          });

The functor or lambda is probably your best choice here. Making an operator< for this class says that you always want to sort by first name, which is probably not true in general for names.

Collin
  • 11,977
  • 2
  • 46
  • 60