我之前有一个关于按名称、ID 和金额组织一些输入的问题。现在我已经弄清楚如何组织它们,我需要有 3 个输出;第一个按名称,第二个按 ID,最后一个按金额。我可以使用 case 和 switch 语句吗?每次我尝试时,所有三个输出都是按名称命名的。
这是我目前所拥有的:
void GeneralSort(const int SortItem, const int count, CustomerProfile c[])
{
string tempname;
string tempid;
float tempamount;
for(int iteration = 1; iteration < count; iteration ++)
{
for(int n = 0; n < (count-iteration); n++)
{
if(c[n].CustomerName > c[n+1].CustomerName)
{
tempname = c[n].CustomerName;
c[n].CustomerName = c[n+1].CustomerName;
c[n+1].CustomerName = tempname;
}
if(c[n].CustomerId > c[n+1].CustomerId)
{
tempid = c[n].CustomerId;
c[n].CustomerId = c[n+1].CustomerId;
c[n+1].CustomerId = tempid;
}
if(c[n].AmountDue > c[n+1].AmountDue)
{
tempamount = c[n].AmountDue;
c[n].AmountDue = c[n+1].AmountDue;
c[n+1].AmountDue = tempamount
}
我如何获取其余数据,以便它具有按 ID 输出的第二个输出和按数量输出的第三个输出。我认为您可以添加 switch 语句,但当我累了时,所有三个输出都按第一组显示,即按名称显示。任何帮助表示赞赏。我不指望任何人为我解决所有问题,只是为我指明正确方向的提示。
输出示例:
//by name
name id amount
able b2 24
bob g3 68
carry a4 12
//by id
name id amount
carry a4 12
able b2 24
bob g3 68
//by amount
name id amount
carry a4 12
able b2 24
bob g3 68
最佳答案
您现在使用函数所做的是混合数据的属性,而不是对其进行排序。您应该使用一个标志来区分要排序的列,或者使用 3 个函数 sortByName、sortByID 和 sortByAmout。你的ifs是错误的。而不是
if(c[n].CustomerName > c[n+1].CustomerName)
{
tempname = c[n].CustomerName;
c[n].CustomerName = c[n+1].CustomerName;
c[n+1].CustomerName = tempname;
}
应该是这样的
CustomerProfile tempItem;
if(c[n].CustomerName > c[n+1].CustomerName)
{
tempItem = c[n];
c[n] = c[n+1];
c[n+1] = tempItem;
}
关于c++ - 用结构和数组切换结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/878387/