c ++用结构排序 [英] c++ sort with structs

查看:19
本文介绍了c ++用结构排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难解决这个需要某种客户姓名、客户 ID 以及最终应付金额的问题.我已经弄清楚了整个程序,但无法弄清楚进行排序所需的最后一个原型.我有一个名为客户的结构,我还将提供 int main() 部分.我只需要任何帮助就可以开始使用原型 SortData().

I am having a hard time with this problem which requires a sort of customer names, customer ids, and finally amount due. I have the whole program figured, but cannot figure out the last prototype needed to do the sorting. i have a struct called Customers, and i will provide the int main() part also. I just need any help to gt started on the 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,在 中声明> 标题.

You should use C++'s standard sort function, std::sort, declared in the <algorithm> header.

当您使用自定义排序函数进行排序时,您必须提供一个谓词函数来说明左侧值是否小于右侧值.因此,如果您想先按名称排序,然后按 ID 排序,然后按到期金额排序,全部按升序排序,您可以这样做:

When you sort using a custom sorting function, you have to provide a predicate function that says whether the left-hand value is less than the right-hand value. So if you want to sort by name first, then by ID, then by amount due, all in ascending order, you could do:

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 调用:

Now, pass that function to your sort call:

std::sort(customers.begin(), customers.end(), &customer_sorter);

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

This assumes you have an STL container (and not an array, like you have in your sample code) called customers containing customers.

这篇关于c ++用结构排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆