我几乎整夜都在尝试让这种排序代码正常工作,无论如何我在这行代码中遇到了最后一个错误:
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 函数也可以。
关于c++ - 尝试对结构 A-Z 文件进行排序时出现排序函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15215341/