Sort函数在尝试对结构体a - z的文件进行排序时发生错误

Error on a Sort function error while trying to sort a file of structs A-Z

本文关键字:文件 排序 错误 函数 结构体 Sort      更新时间:2023-10-16

我一直试图让这种类型的代码工作几乎整个晚上,无论如何,我得到这行代码的最后一个错误:

if(A[c]>A[c+1]) swap(A,c,c+1);

它在>上给我一个错误,说没有操作符匹配这些操作数。如果我在输入或输出时弄乱了>><<,我以前见过这个错误,但这是一个完全不同的问题。

整个代码:

   #include <iostream>
#include <string>
#include <fstream>
#include <algorithm> 
using namespace std;
struct salesTran {
string name;
double quantity,price;
};
bool compareByPrice(salesTran const &a, salesTran const &b)
    {
    return a.price < b.price;
}
void swap(salesTran A[], int i, int j);
void sort(salesTran A[], int size);
ostream& operator << (ostream& os, salesTran A)
{os << A.name << "t" << A.quantity << "t" << A.price;
return os;}
istream& operator >> (istream& is, salesTran& A)
{is >> A.name >> A.quantity >> A.price;
return is;}
int main()
{
   salesTran data[250];
ifstream fin;
fin.open("sales.txt");
ofstream fout;
fout.open("results.txt");
int index = 0;
fin >> data[index];
while(!fin.eof())
{
index++;
fin >> data[index];
}
sort(data, index);
for(int j=0; j < index; j++)
{ 
cout << data[j] << endl;
}
return 0;
}
void swap(salesTran A[], int i, int j)
{
salesTran temp;
temp =A[i];
A[j] = A[j];
A[j] = temp;
return;
}

bool compareByPrice(salesTran const &a, salesTran const &b)
{
    return a.price < b.price;

std::sort(data, data + index, compareByPrice);
return;
}

salesTran上重载operator>将是一个坏主意,因为salesTran的每个字段都是比较两个事务的完全有效的方法。阅读您的代码(或API!)的人将不得不查看文档以找出使用的是哪个。

相反,您可以定义一个比较函数并使用std::sort:
#include <algorithm>
bool compareByPrice(salesTran const &a, salesTran const &b)
{
    return a.price < b.price;
}
std::sort(data, data + index, compareByPrice);

如果你喜欢的话,c++ 11的lambda函数也可以。

问题很可能源于您试图比较的数据类型,例如,使用>关系运算符比较两个整数是可行的,因为它支持这种类型的比较。但是,不能用这种方式比较两个数组,因为内置的关系操作符不是用来比较整个数组的。这样做的唯一方法是重载操作符本身。

http://www.cplusplus.com/doc/tutorial/classes2/