The compiler gives a mistake :Expression: invalid operator<. I think there should be a problem with the parameters, which receive the comparator, but I am not sure. Here is the code.
#include<iostream>
#include<fstream>
#include<algorithm>
using namespace std;
struct ticket{
char destination[50];
char flightNumber[50];
char Aircraft[50];
};
bool comparator(ticket a, ticket b)
{
return a.destination < b.destination;
}
int main()
{
const int SIZE = 6;
char mydestination[40];
ticket newA[SIZE];
fstream f;
f.open("records.dat", ios::in | ios::binary);
if (f.is_open())
{
f.read(reinterpret_cast<char*>(newA), SIZE *sizeof(ticket));
f.close();
}
else
cout << "ERROR\n";
sort(newA, newA SIZE, comparator);
for (ticket& s : newA)
{
cout << s.destination;
cout << s.Aircraft;
cout << s.flightNumber << endl;
}
system("pause");
return 0;
}
CodePudding user response:
As mentioned in the comments, using <
will just compare addresses.
To actually compare the strings you can use std::lexicographical_compare. Change your comparator to
bool comparator(const ticket& a, const ticket& b) {
return std::lexicographical_compare(std::begin(a.destination), std::end(a.destination), std::begin(b.destination), std::end(b.destination));
}
CodePudding user response:
Your "strings" are not c , they are arrays of characters in c style. Therefore the best option for you is, as is suggested in the comments, to use:
int strcmp (const char* str1, const char* str2);
bool comparator(ticket a, ticket b)
{
return strcmp(&a.destination,&b.destination);
}
Or just delete comparator function and use:
sort(newA, newA SIZE, strcmp(&a.destination,&b.destination));
You may need
#include <string.h>
But I would better rewrite my code in c style