简体   繁体   English

c ++使用结构排序

[英]c++ sort with structs

I am having a hard time with this problem which requires a sort of customer names, customer ids, and finally amount due. 我很难解决这个问题,需要一种客户名称,客户ID,最后是应付金额。 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. 我有一个名为Customers的结构,我也将提供int main()部分。 I just need any help to gt started on the prototype SortData(). 我只需要任何帮助来启动原型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
}

You should use C++'s standard sort function, std::sort , declared in the <algorithm> header. 您应该使用C ++的标准排序函数std::sort ,在<algorithm>标头中声明。

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: 因此,如果您希望先按名称排序,然后按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;
}

Now, pass that function to your sort call: 现在,将该函数传递给您的sort调用:

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

This assumes you have an STL container (and not an array, like you have in your sample code) called customers containing customers. 这里假设你有一个STL容器(而不是一个数组,就像你在你的示例代码中有)称为customers包含客户。

Its often overlooked that you can actually use STL range functions with C based arrays, like in your example. 经常忽略的是,您可以将STL范围函数与基于C的数组一起使用,就像在您的示例中一样。 So you don't actually have to move over to using an STL based container (I won't debate the merits of doing that here :-)). 所以你实际上不必转向使用基于STL的容器(我不会在这里讨论这样做的优点:-))。

So, building on the answer from Chris, you could invoke sort as follows: 因此,基于Chris的答案,您可以调用如下排序:

std::sort( customers, customers+Count, &customer_sorter);

You only need to write a comparison function that compares two CustomerProfile types. 您只需要编写一个比较两个CustomerProfile类型的比较函数。 Once you have this function, you can use either the STL sort (see http://www.sgi.com/tech/stl/sort.html or http://msdn.microsoft.com/en-us/library/ecdecxh1(VS.80).aspx ) or the old C qsort: http://en.wikipedia.org/wiki/Qsort_(C_Standard_Library) . 完成此功能后,您可以使用STL排序(请参阅http://www.sgi.com/tech/stl/sort.htmlhttp://msdn.microsoft.com/en-us/library/ecdecxh1 (VS.80).aspx )或旧的C qsort: http//en.wikipedia.org/wiki/Qsort_( C_Standard_Library I would advise against writing your own sort algorithm, unless this is a homework assignment. 我建议不要编写自己的排序算法,除非这是一个家庭作业。 Your comparison depends on the technology you like to use, it could look do something like this: 您的比较取决于您喜欢使用的技术,它可能看起来像这样:

int CompareCustomerProfile(
   const CustomerProfile* pC1,
   const CustomerProfile* pC2)
{
 int result = strcmp(pC1->name, pC2->name);
 if (0 != result) return result; 

  result = strcmp(pC1->ID, pC2->ID);
  if (0 != result) return result;

  if (pC1->amountDue < pC2->amountDue) return -1;
 if (pC1->amountDue > pC2->amountDue) return 1;

  return 0
}

this assumes that the 'string' type in your example is a char*. 这假设您的示例中的'string'类型是char *。 If you use Unicode or multibyte types then the appropriate Unicode or multibyte comparison has to be used, obviously. 如果使用Unicode或多字节类型,则显然必须使用适当的Unicode或多字节比较。 Then you would just call the algorithm, with your comparison function. 然后你只需用比较函数调用算法。 Eg. 例如。 using qsort: 使用qsort:

qsort(c, Count, sizeof(CustomerProfile), CompareCustomerProfiler).

Now if this is a homework assignment, you shouldn't be asking here how to do it... 现在,如果这一个家庭作业,你不应该问这里怎么做...

You can find a lot of sort implementations in C++ with creative googling.. The only difference is that instead of sorting numbers, you are sorting structs. 您可以使用创意Google搜索在C ++中找到许多排序实现。唯一的区别是,不是排序数字,而是排序结构。

So wherever there is something like if(a[i]<a[j]) in the algorithm you will use, make a call like `if(isFirstCustomerLowerThanOther(a[i] 因此,无论你在算法中使用if(a[i]<a[j]) ,都会调用`if(isFirstCustomerLowerThanOther(a [i])

Now, create a function with the following structure: 现在,使用以下结构创建一个函数:

bool isFirstCustuomerLowerThanOther(const Customer& firstCustomer, const Customer& secondCustomer)
{
 // Implement based on your key preferences
}

Even better, if you use C++ you can use the STL's sort algortihm (again, google for info and for how to pass an ordering to it. 更好的是,如果你使用C ++,你可以使用STL的排序algortihm(再次,google获取信息以及如何将订单传递给它。

I assume that you are new to programming or in C++, so here is what you probably are looking for: 我假设你是编程或C ++的新手,所以这里是你可能正在寻找的东西:

#include <search.h> // for the qsort()

int
CompareByName( const void *elem1, const void *elem2 )
{
  return ((Customers*)elem1)->Name > ((Customers*)elem2)->Name? 1 : -1;
}

int
CompareByOrderAmount( const void *elem1, const void *elem2 )
{
  return ((Customers*)elem1)->OrderAmount > ((Customers*)elem2)->OrderAmount? 1 : -1;
}

void SortData( int SortItem, int count, Customers customers[] )
{
  switch (SortItem) {
  case 0:
    qsort(customers, count, sizeof(Customers), CompareByName);
    break;
  case 1:
    qsort(customers, count, sizeof(Customers), CompareByOrderAmount);
    break;
  // ...
  }
}

void test()
{
  Customers cust[10];

  cust[0].Name = "ten";
  cust[1].Name = "six";
  cust[2].Name = "five";
  SortData( 0, 3, cust );
  cout << cust[0].Name << endl;
  cout << cust[1].Name << endl;
  cout << cust[2].Name << endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM