I have a game in which the main goal - to hold out as long as possible. Who lasted longer - that is supposedly the best player. After each session of the game, request the name of the player, and this information is recorded in the file top.txt in the following format:

количСство_сСкунд/имя_ΠΈΠ³Ρ€ΠΎΠΊΠ° 

To make it clear, the file looks like this:

screen

It is necessary to display the sorted results in the console. I tried sort when working with a vector like this:

 vector<string> v; ifstream in("top.txt"); char buf[256]; while(in.getline(buf,256)) v.push_back(buf); std::sort(v.begin(),v.end()); std::reverse(v.begin(),v.end()); for(vector<string>::iterator s = v.begin(); s != v.end(); ++s) cout << s->c_str() << endl; 

That is, we sort , turn over and display all the elements. It would seem so? But the result is not the way I would like to see it:

result

Results with 127, 1223, 11 and 10 seconds should be higher than, for example, 9.

This is my second similar question. The first is here . The proposed option worked only when all the code was located in one main.cpp file, breaking the program into a couple of classes received errors. The same code, except that the function was used for comparison: sort(v.begin(),v.end(),compare); And the function itself is as follows:

 bool Menu::compare(const string& s1, const string& s2) { return atoi(s1.c_str()) > atoi(s2.c_str()); } 

The code is higher in Menu.cpp, the function prototype in Menu.h:

 bool compare(const std::string& s1, const std::string& s2); 

For a very long time, the compiler cursed string, in the end, Google gave advice that you should use std. And this is what the compiler produces for this sorting method:

error

Please tell me a simple way of sorting, or my cant, why such errors are incomprehensible. All that is necessary for the code will provide.

Yes, if that: Code :: Blocks 16.01, GNU GCC Compiler

  • Break the string into the structure and sort the vector of structures. - Qwertiy ♦

1 answer 1

The problem is that strings are compared character by character, and you want to compare numbers. The solution may be to compare the numbers with which the lines begin, which you basically are trying to do.

 #include <iostream> #include <vector> #include <fstream> #include <algorithm> using namespace std; int main() { auto comparator = [](string s0, string s1) { int first_number0 = atoi(s0.c_str()); int first_number1 = atoi(s1.c_str()); return first_number0 > first_number1; }; vector<string> lines; ifstream in("top.txt"); string line; while (getline(in, line)) { lines.push_back(line); } sort(lines.begin(), lines.end(), comparator); for (string line : lines) { cout << line << endl; } return 0; }