Search code examples
c++stringsortingc++11stdstring

How to sort strings on two conditions without an array/algorithms in c++?


I am trying to do a program where a user inputs three names and they get sorted. The conditions are that each name gets inputted like "firstname lastname" and then I need to sort the names on lastname, but if the lastname is the same for two entries I need to sort on the firstname.

I have solved how to sort on just the firstname OR lastname, but am getting stuck on how to sort on both. Any ideas how I can implement more conditional sorting without using an array or <algorithm> in c++?

For each input I do this to split the input to firstname and lastname to lowercase:

cout << "Input name1: " << endl;
getline(cin, input1);
input1_old = input1;

size_t found = input1.find(space);
for (int i = 0; i < input1.size(); i++)
{
    input1[i] = tolower(input1[i]);
}
input1Last = input1.substr(found + 1, string::npos);
input1First = input1.substr(0, found);

Then I "sort" like this:

if (input1Last <= input2Last && input2Last <= input3Last)
{
    cout << input1_old << '\n' << input2_old << '\n' << input3_old << endl;
}
else if (input1Last <= input3Last && input3Last <= input2Last)
{
    cout << input1_old << '\n' << input3_old << '\n' << input2_old << endl;
}
else if (input2Last <= input1Last && input1Last <= input3Last)
{
    cout << input2_old << '\n' << input1_old << '\n' << input3_old << endl;
}
else if (input2Last <= input3Last && input3Last <= input1Last)
{
    cout << input2_old << '\n' << input3_old << '\n' << input1Last << endl;
}
else if (input3Last <= input1Last && input1Last <= input2Last)
{
    cout << input3_old << '\n' << input1_old << '\n' << input2_old << endl;
}
if (input3Last <= input2Last && input2Last <= input1Last)
{
    cout << input3_old << '\n' << input2_old << '\n' << input1Last << endl;
}

Solution

  • To swap first and last names, use the following trick:

    • Reverse the entire string
    • Reverse the individual names in the string

    To do this, you should write a function that reverses a string between two indices, and you will need to use string::find() (or a loop) to find the space between the names.

    To sort three items, use the following trick:

    • sort the first two items
    • sort the last two items
    • sort the first two items

    Again, sorting two items is perfect for a function.

    Hints:

    void reverse( string& s, int first, int last );
    void sort( string& a, string& b );  // swap a and b if !(a < b)