Sort函数在尝试对结构体a - z的文件进行排序时发生错误
Error on a Sort function error while trying to sort a file of structs A-Z
我一直试图让这种类型的代码工作几乎整个晚上,无论如何,我得到这行代码的最后一个错误:
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++
- 使用C++对一个巨大文件中的文本行进行字典式外部排序
- 如何按升序对输入文件中的数字进行排序,并找到它们的范围和中值
- 如何在一个巨大的文本文件中对整数进行排序
- 在排序链表中插入结构并将其写入二进制文件
- 从文件中读取并将其内容放入对象数组中,然后对它们进行排序
- 对包含整数的文本文件进行排序时,必须逐行进行排序
- 在排序文本文件中实现二叉搜索?
- 如何从输入的文本文件中按姓氏字母顺序对图表进行排序?
- 按文件中列表中行的一部分排序
- C++ 从文件中获取数据时使用 strcpy 和 strcmp 按字母顺序对数组进行排序?
- 如何从文件中读取并按类别对它们进行排序
- 如何在大型文本文件中对数字进行排序
- C++ 从文件中读取字符,计算每个字符并进行排序
- 从文件中读取并按字母顺序排序
- 随机化超大文件内容排序的有效方法是什么?
- 为什么名称在我的数组中重复出现,以及如何使TXT文件排序
- c++二进制文件排序
- 合并两个文本文件排序