Sorting Strings

Hi,I am printing out information and it works successfully, however i wish to print it lexicographically\alphabetically by comparing the last name strings stored into this vector that i am printing. How can I do this.

Here is my code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void printStudent()
{
    system("cls");
    cout << "Records\n-------------------------\n\n";
    
      
    
    //Loops through the vector that stores the student objects
    for(int i = 0; i < students -> size(); i++)
    {
      students -> at(i).print();
    }
    
    system("Pause");
} 
Last edited on
You can have the standard sort function do the job for you. Declare & define a function that compares two students:

1
2
3
4
bool is_less(const Student & s1, const Student & s2)
{
     return s1.m_last_name.compare(s2.m_last_name)<0;
}

And then do the sorting like this:
sort(student_vector.begin(),student_vector.end(),is_less);

Info on compare -> http://cplusplus.com/reference/string/string/compare/
Info on sort -> http://cplusplus.com/reference/algorithm/sort/
Last edited on
Cheers r0shi, will give this a go.
Topic archived. No new replies allowed.