我很难解决这个问题,它需要一种客户姓名、客户 ID 以及最后的应付金额。我已经计算了整个程序,但无法确定进行排序所需的最后一个原型(prototype)。我有一个名为 Customers 的结构,我还将提供 int main() 部分。我只需要任何帮助来启动原型(prototype) SortData()。
struct Customers {
string Name;
string Id;
float OrderAmount;
float Tax;
float AmountDue;
};
const int MAX_CUSTOMERS = 1000;
bool MoreCustomers(int);
Customers GetCustomerData();
void OutputResults(Customers [], int);
void SortData(const int, const int, Customers []);
int main() {
Customers c[MAX_CUSTOMERS];
int Count = 0;
do {
c[Count++] = GetCustomerData();
} while (MoreCustomers(Count));
for (int i = 0; i < Count; i++) {
c[i].Tax = 0.05f * c[i].OrderAmount;
c[i].AmountDue = c[i].OrderAmount + c[i].Tax;
}
SortData(0, Count, c); //0:Sorts by customer name
OutputResults(c, Count);
GeneralSort(1, Count, c); //1:Sorts by ID
OutputResults(c, Count);
GeneralSort(2, Count, c); //2: Sorts by amount due
OutputResults(c, Count);
return 0;
}
void SortData(const int SortItem, const int count, CustomerProfile c[]) {
//0: Sort by name
//1: Sort by ID
//3: Sort by amount due
}
最佳答案
您应该使用 C++ 的标准排序函数 std::sort
,在 <algorithm>
中声明标题。
当您使用自定义排序函数进行排序时,您必须提供一个 谓词函数 来说明左侧值是否小于右侧值。因此,如果您想先按名称排序,然后按 ID 排序,然后按到期金额排序,所有这些都按升序排列,您可以这样做:
bool customer_sorter(Customer const& lhs, Customer const& rhs) {
if (lhs.Name != rhs.Name)
return lhs.Name < rhs.Name;
if (lhs.Id != rhs.Id)
return lhs.Id < rhs.Id;
return lhs.AmountDue < rhs.AmountDue;
}
现在,将该函数传递给您的 sort
调用:
std::sort(customers.begin(), customers.end(), &customer_sorter);
这假设您有一个名为 customers
的 STL 容器(而不是数组,就像您在示例代码中使用的那样)。包含客户。
关于c++ 使用结构排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/873715/