編譯器報錯:運算式:無效運算子<。我認為接收比較器的引數應該有問題,但我不確定。這是代碼。
#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;
}
uj5u.com熱心網友回復:
正如評論中提到的,使用<只會比較地址。
要實際比較字串,您可以使用std::lexicographical_compare。將您的比較器更改為
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));
}
uj5u.com熱心網友回復:
您的“字串”不是 C ,它們是 C 風格的字符陣列。因此,正如評論中所建議的那樣,對您來說最好的選擇是使用:
int strcmp (const char* str1, const char* str2);
bool comparator(ticket a, ticket b)
{
return strcmp(&a.destination,&b.destination);
}
或者只是洗掉比較器函式并使用:
sort(newA, newA SIZE, strcmp(&a.destination,&b.destination));
你可能需要
#include <string.h>
但我最好用 C 風格重寫我的代碼
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/344659.html
上一篇:C中一個檔案到另一個檔案的轉換
下一篇:什么進入檔案頭?
