c ++使用结构排序

15 c++ arrays sorting struct bubble-sort

我很难解决这个问题,需要一种客户名称,客户ID,最后是应付金额.我有整个程序,但无法弄清楚进行排序所需的最后一个原型.我有一个名为Customers的结构,我也将提供int main()部分.我只需要任何帮助来启动原型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
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*ung 37

您应该使用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;
}
Run Code Online (Sandbox Code Playgroud)

现在,将该功能传递给您的sort电话:

std::sort(customers.begin(), customers.end(), &customer_sorter);
Run Code Online (Sandbox Code Playgroud)

这假设您有一个名为customers包含客户的STL容器(而不是您的示例代码中的数组).


Cod*_*ddy 13

经常忽略的是,您可以将STL范围函数与基于C的数组一起使用,就像在您的示例中一样.所以你实际上不必转向使用基于STL的容器(我不会在这里讨论这样做的优点:-)).

因此,基于Chris的答案,您可以调用如下排序:

std::sort( customers, customers+Count, &customer_sorter);
Run Code Online (Sandbox Code Playgroud)