c++ 使用结构排序

标签 c++ arrays sorting struct bubble-sort

我很难解决这个问题,它需要一种客户姓名、客户 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/

相关文章:

c++ - 我可以删除在另一个进程中创建的 HBITMAP 对象吗?

c++ - 如果在调试器中运行,数据在 Visual Studio 中未正确对齐

c - 计算文件中音节数的程序

java - 在每个 JTextArea 中显示迭代

c++ - 从 C++11 中的多个线程获取值,而无需等待任何给定线程完成执行

数组中对象的 C++ 多态性

ios - 将列表排序为 TableView 索引的部分

java - 有没有比使用数组更简单的拆分字符串的方法?

php - 如何同时按数字和字母顺序对 varchar 查询列进行排序

通过将字符串转换为日期格式来对 Javascript 日期进行排序