Sorting Names Alphabetically

I've been assigned to write the following function:
void sort(vector<string>&, char); – Sorts the vector of names in either ascending(alphabetical) order, depending on the third argument.
The names are first name and last name. The code I have written so far is only capable of handling only names without white space. Can someone explain how to edit this code to take that into consideration?

1
2
3
4
5
6
7
8
9
10
11
12
//sort names in alphabetical order
void sort(vector<string>&names, char first){
string swap;
for (size_t i = 0; i < names.size(); i ++){
for (size_t j = 0; j < names.size(); j ++){
if (names[i] > names[i+1]){ // which alphabetically comes later?
swap = names[i];
names[i] = names[i+1];
names[i+1] = names[i];
}
}
}
void sort(vector<string>&, char); – Sorts the vector of names ... depending on the third argument.
I see only two parameters.
I see no use of the 'first'.

Those aside, it sounds like an element in vector 'names' is a string that contains a full name, for example "John Doe". We think that we see in it two words ("forename" and "surname"), but for your algorithm it is just one string.

If there are only two words in each name, then we know that there is one whitespace. (Some people have more than two words in their name and that is much more complicated.)

Lets assume two words. Now we concentrate on the (names[i] > names[i+1]).
You could make a separate function that takes two strings and returns a bool (just like the > does).

For each string, find the position of the whitespace. With that information you can refer to the substrings before and after the whitespace. Now you can compare forenames and surnames separately.


Now we can get back to the "third" argument. We have so far used > to determine the "wrong order". The "third" argument should be used to select what is appropriate comparison.
Another way to do it, is use a sort algorithm that compares the two strings. The only difference is that you would be able to remove case-sensitivity.
Topic archived. No new replies allowed.