c++ - 尝试对结构 A-Z 文件进行排序时出现排序函数错误

标签 c++ arrays sorting struct swap

我几乎整夜都在尝试让这种排序代码正常工作,无论如何我在这行代码中遇到了最后一个错误:

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/

相关文章:

c++ - 为什么 std::unique_ptr 阻止访问被销毁的对象?

c++ - 基本深拷贝(操作重载)

C中的数组可以存储在非顺序指针中吗?

javascript - 对象或数组或两者

c++ - 我需要帮助了解如何在 C++ 中对包含多个带空格的字符串的集合或 vector 进行排序

python - 如何对字符串中的混淆数字列表进行排序?

c++ - 我正在尝试在C++上做傻瓜练习,但遇到错误,说 'GraduateStudent'类没有名为 'advisor'的任何字段

c++ - iphone 的贝叶斯网络库?

php - 检查字符串是否包含数组中的值

javascript - 如何使用 map 函数和给定索引设置数组元素的特定位置?