c++ - 用结构和数组切换结构?

标签 c++ sorting struct

我之前有一个关于按名称、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/

相关文章:

c++ - 如何为 std::string 可变参数模板参数调用 c_str()?

c++ - 将 C 编译为 C++ 链接器错误(lua 和 oolua)

c++ - 计算大于 400mb 的大文件的 sha-1 或 CRC32 校验和

c++ - 如何通过成员函数指针调用基类方法?

python - python中堆元素的比较顺序

c - 添加另一条记录到动态内存数据库时出错

ios - 如何基于多个属性和非属性(方法)对NSMutableArray进行排序

python - 如何根据数值的顺序对包含组合数值和文本值的列表进行排序

c - 将动态分配结构的元素置零或清除的有效方法

c++ - MySQL源代码中 "struct PSI_thread"的定义在哪里?