'Sorting an array of strings in C++

I am trying to accomplish the following task:

List the students in alphabetic order, sorted by last name. Do not change the given case of the names. Do not change the output file format. (Firstname Lastname) Just print the records in order by last name, i.e.

Annie J

Martin K

Toby L

This sort needs to be true alphabetical (not just the "lexicographical" sort).

The data was read in from a file and passed through a virtual function depending on what course this student was enrolled in. Here's what I have.

for (int i = 1; i < numStudents; i++)
{
   if (( list[i] -> getLastname() ) < ( list[i - 1] -> getLastname() ))
   { 
       Student *temp = list[i - 1];
       ist[i - 1] = list[i];
       list[i] = temp;
   }
}

I've been working on this for a while now and I'm worried I've gone about this all wrong. Any tips/pointers appreciated!



Solution 1:[1]

I assume you have a struct like:

struct Student
{
    std::string m_LastName;
    std::string m_FirstName;
};

Now you need to make sure you can handle the case where two person have the same last name. In that case you want to look at the first name.

bool NameCompare(const Student &name1, const Student &name2)
{
    if(name1.m_LastName == name2.m_LastName) {
        return name1.m_FirstName < name2.m_FirstName;
    }

    return name1.m_LastName < name2.m_LastName;

}

Then just call sort on your list of Student

std::list<Student> student_list;
// add some Student to the list
student_list.sort(NameCompare);

Solution 2:[2]

Use string comparison function instead of the less than sign you used here:

if (( list[i] -> getLastname() ) < ( list[i - 1] -> getLastname() ))

Also here's a similar stackoverflow question (partially)

Is string::compare reliable to determine alphabetical order?

Solution 3:[3]

Try this reference, first you have to declare the size of the array of firstname and lastname using int z = sizeof(lastname, firstname)/sizeof(lastname[0], firstname[0]); and using sort(lastname,lastname+z); will sort the array of lastname then using loop to print the firstname with the sorted lastname.

#include <string>
#include <algorithm>
#include <iostream>
using namespace std;

int main()
{
string firstname[] = {"Michael", "Patricia", "Joseph", "Elizabeth", "Charles", "Barbara", "Thomas", "Margaret", "Robert", "Sarah"};
string lastname[] = {"Smith", "Johnson", "Williams", "Brown", "Jones", "Miller", "Davis", "Garcia", "Rodriguez", "Wilson"};

int z = sizeof(lastname, firstname)/sizeof(lastname[0], firstname[0]);

sort(lastname,lastname+z); //Use the start and end like this
for(int y = 0; y < z; y++){
cout << firstname[y]<< " " << lastname[y] << endl;
}
return 0;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eric Pruneau
Solution 2 Community
Solution 3