1

如何显示项目的名称?因此,输出是最低的商品价格和商品名称。是否可以在排序部分显示项目名称?

图像是编译结果

void bubble_sort()
{
    int b[] = {3800,1900,2700,2200,5000};
    int i,j,tmp;
    for(i=0; i<5; i++)
   {
       for(j=i+1; j<5; j++)
      {
          if(b[i]>b[j])
         {
            tmp = b[i];
            b[i]= b[j];
           b[j]= tmp;
         }
      }
   }
   for(i=0; i<5; i++)
   {
       cout<<" \tRp. "<<b[i];
       cout<<endl;
   }
}
4

2 回答 2

1

在 C++ 中,一些对象有名称,但许多其他对象没有。在您的情况下,数组对象具有 name b,但数组成员是没有名称的子对象。b[0]您可以通过表达式to来引用它们b[4]。如果查看这些表达式,您会看到两个子表达式(名称b和整数)由 . 连接operator[]。你甚至可以有类似的表达式b[i],其中子表达式bi都是名称。

此外,将有多个表达式引用同一个对象。例如,*(b+2)是与 相同的对象b[2]

即使对于确实有名称的对象,该名称也只有编译器知道。一旦您的程序运行,该名称将不再存在(可能在调试信息中除外)。

于 2021-04-13T12:34:38.920 回答
0

您可以使用以下内容将商品名称及其价格关联在一起struct

struct Stuff {
    std::string name;
    int price;
};

然后有一个数组Stuff并将其排序为常规数组,但使用每个数组的价格Stuff[i]在它们之间进行排序。

#include <iostream>
#include <string>

struct Stuff {
    std::string name;
    int price;
};

int main() {
    Stuff collection[] = {
        {"book", 3800},
        {"eraser", 1900},
        {"pencil", 2700},
        {"ruler", 2200},
        {"pen", 5000}
    };

    size_t collectionSize = std::size(collection); // 5

    //Same logic...
    int i,j;
    for(i=0; i < collectionSize; i++)
    {
        for(j = i +1; j < collectionSize; j++)
        {
            if(collection[i].price > collection[j].price)
            {
                Stuff tmp = collection[i];
                collection[i] = collection[j];
                collection[j] = tmp;
            }
        }
    }

    //Print the item name and the price
    for(i =0 ; i < collectionSize; i++)
    {
        std::cout<<collection[i].name<<" \tRp. "<<collection[i].price<<"\n";
    }
}
于 2021-04-13T14:26:23.927 回答