是否有某种方法可以将这段代码转换为5行,这似乎很重复。
我想使用开关盒。另外,我想将其保持在初学者水平。
void SortProductList(Product *productList, int size, char sortOption){
Product temp;
for (int i=0; i<size-1; i++)
{
for (int j=i+1; j<size; j++)
{
if (sortOption == 'p') //sorting by price
{
if (productList[j].productPrice<productList[i].productPrice) //second is bigger than first
{
temp = productList[i];
productList[i] = productList[j];
productList[j]=temp;
}
}
if (sortOption == 'w') //sorting by weight
{
if (productList[j].productWeight<productList[i].productWeight) //second is bigger than first
{
temp = productList[i];
productList[i] = productList[j];
productList[j]=temp;
}
}
if (sortOption == 'n') //sorting by weight
{
if (strcmp(productList[j].productName,productList[i].productName)<0) //second is bigger than first
{
temp = productList[i];
productList[i] = productList[j];
productList[j]=temp;
}
}
}
}
}
答案 0 :(得分:3)
Switch语句似乎并不能使您更进一步,请尝试以下操作:
for (int i = 0; i < size - 1; i++){
for (int j = i + 1; j < size; j++){
if ((sortOption == 'p' && productList[j].productPrice < productList[i].productPrice) ||
(sortOption == 'w' && productList[j].productWeight < productList[i].productWeight) ||
(sortOption == 'n' && (strcmp(productList[j].productName, productList[i].productName) < 0))){
temp = productList[i];
productList[i] = productList[j];
productList[j] = temp;
}
}
}