Hello, I am working on an assignment where we need to sort a list of names and corresponding grades into alphabetical order, but my code is not sorting. The inputs are in the format of John Smith with a space in the middle. I might make another topic for it but if someone can also answer how to sort by last name when it is in a single string that would be great to. Thanks!
The index variable of the inner loop is j, but you are using i for the comparison.
1 2 3 4 5 6 7 8 9 10 11 12
void SortByFirstName(vector<string>& students, vector<double>& grades) {
for (int i = 0; i < int(students.size()) - 1; ++i) {
int min = i;
for (int j = i + 1; j < int(students.size()); ++ j)
if (students[j] < students[min])
min = j;
if (min != i) {
swap(students[i], students[min]);
swap(grades[i], grades[min]);
}
}
}
The int casts on .size() serve two purposes: they silence a compiler warning, and it fixes a bug that your code would've had if passed a zero-length vector. size() returns an unsigned value. An unsigned 0 minus 1 yields the maximum unsigned value, which would certainly blow your code up.