Hello! You need to write a program that sorts the names alphabetically. The beginning is the first big letter. Here is my code:

#include <iostream> #include <fstream> #include <algorithm> #include <string> #include <ctime> using namespace std; bool Compare(string name1, string name2) { string temp1 = ""; string temp2 = ""; bool b = false; for (int i = 0; i < name1.length(); i++) { if ((name1[i] >= 'A')&&(name1[i]<='Z')) { b = true; } if (b) temp1 += name1[i]; } b = false; for (int i = 0; i < name2.length(); i++) { if ((name2[i] >= 'A') && (name2[i] <= 'Z')) { b = true; } if (b) temp2 += name2[i]; } if (temp1 == temp2) return true; int length; if (temp1.length() == temp2.length()) length = temp1.length(); else length = min(temp1.length(), temp2.length()); for (int i = 0; i < length; i++) { if (temp1[i] > temp2[i]) return false; if (temp1[i] < temp2[i]) return true; } return true; } void main() { ifstream fin("NAMES.IN"); string temp; getline(fin, temp); long N = stoi(temp); string *names = new string[N]; for (int i = 0; i < N; i++) getline(fin, names[i]); sort(names, names + N, Compare); for (int i = 0; i < N; i++) cout << names[i] << endl; } 

It works fine as long as all the names are different. If they are the same, the error "invalid comparator" appears. Please tell me how to write it correctly so that this error does not exist.

  • And if the line does not contain capital letters, then what? Or if the line contains two words with a capital letter? - Vlad from Moscow
  • Each line has a capital letter. How many words and how many capital letters do not matter. It is still considered as one. - Mikhail Veselov

1 answer 1

You have an error in that the comparator (it is roughly a sign less) with equal objects must return false. Otherwise, the symmetry property will be violated. And maybe even looping.

Replace if (temp1 == temp2) return true; to false . And return true;} on return temp1.length() < temp2.length() .

There is still an error when one last name in your definition is the prefix of the second.

And by the way, this will only be in the debug version of the program, when the compiler (especially ms vc ++) makes calls to cmp (a, b) and cmp (b, a). In the release of this error will not. But there can be an exit for array boundaries or looping.

  • Uh ... A comparator is, roughly speaking, a smaller ratio, so with equal it should return false ... - Harry
  • @Harry yes) so I formulated) - pavel