c ++用结构排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/873715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c++ sort with structs
提问by Chris Jester-Young
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().
我在解决这个问题时遇到了困难,它需要某种客户名称、客户 ID 以及最后的应付金额。我已经弄清楚了整个程序,但无法弄清楚进行排序所需的最后一个原型。我有一个名为客户的结构,我还将提供 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
}
回答by Chris Jester-Young
You should use C++'s standard sort function, std::sort
, declared in the <algorithm>
header.
您应该使用std::sort
在<algorithm>
头文件中声明的C++ 的标准排序函数。
When you sort using a custom sorting function, you have to provide a predicate functionthat says whether the left-hand value is less thanthe 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.
这假设您有一个名为customers
包含客户的 STL 容器(而不是一个数组,就像您在示例代码中那样)。
回答by CodeBuddy
Its often overlooked that you can actually use STL range functions with C based arrays, like in your example. 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 范围函数与基于 C 的数组一起使用,就像在您的示例中一样。因此,您实际上不必转而使用基于 STL 的容器(我不会在这里讨论这样做的优点:-))。
So, building on the answer from Chris, you could invoke sort as follows:
因此,基于 Chris 的回答,您可以调用 sort 如下:
std::sort( customers, customers+Count, &customer_sorter);
回答by Remus Rusanu
You only need to write a comparison function that compares two CustomerProfile types. Once you have this function, you can use either the STL sort (see http://www.sgi.com/tech/stl/sort.htmlor 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). 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:
您只需要编写一个比较函数来比较两种 CustomerProfile 类型。一旦你有了这个功能,你就可以使用 STL 排序(参见http://www.sgi.com/tech/stl/sort.html或http://msdn.microsoft.com/en-us/library/ecdecxh1 (VS.80).aspx) 或旧的 C qsort: http://en.wikipedia.org/wiki/Qsort_(C_Standard_Library)。我建议不要编写自己的排序算法,除非这是家庭作业。您的比较取决于您喜欢使用的技术,它可能看起来像这样:
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*. If you use Unicode or multibyte types then the appropriate Unicode or multibyte comparison has to be used, obviously. Then you would just call the algorithm, with your comparison function. Eg. using qsort:
这假设您示例中的“字符串”类型是 char*。如果您使用 Unicode 或多字节类型,那么显然必须使用适当的 Unicode 或多字节比较。然后你就可以用你的比较函数调用算法。例如。使用 qsort:
qsort(c, Count, sizeof(CustomerProfile), CompareCustomerProfiler).
Now if this isa homework assignment, you shouldn't be asking here how to do it...
现在如果这是家庭作业,你不应该在这里问怎么做......
回答by Uri
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.
你可以通过创造性的谷歌搜索在 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 的排序算法(再次,谷歌获取信息以及如何将排序传递给它。
回答by Nick Dandoulakis
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;
}