2021-09-20黑马程序员结构体案例2实例
Posted csdn_small_white
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2021-09-20黑马程序员结构体案例2实例相关的知识,希望对你有一定的参考价值。
冒泡排序与结构体数组的结合
#include<iostream>
using namespace std;
struct hero
{
string name;
int age;
string gender;
};
struct hero heroArray[5]
{
{"刘备",23,"男"},
{"关羽",22,"男"},
{"张飞",20,"男"},
{"赵云",21,"男"},
{"貂蝉",19,"女"}
};
void bubbleSort(hero heroArray[], int len)
{
for (int i = 0; i < len; i++)
{
for (int j = 0; j < len - i - 1; j++)
{
if (heroArray[j].age > heroArray[j + 1].age)
{
struct hero temp = heroArray[j];
heroArray[j] = heroArray[j + 1];
heroArray[j + 1] = temp;
/*int temp1 = heroArray[j].age;
heroArray[j].age = heroArray[j + 1].age;
heroArray[j + 1].age = temp1;
string temp2 = heroArray[j].name;
heroArray[j].name = heroArray[j + 1].name;
heroArray[j + 1].name = temp2;
string temp3 = heroArray[j].gender;
heroArray[j].gender = heroArray[j + 1].gender;
heroArray[j + 1].gender = temp3;*/
}
}
}
}
void printinfo(hero heroArray[], int len)
{
for (int i = 0; i < len; i++)
{
cout << "\\t" << heroArray[i].name << " "
<< heroArray[i].age << " "
<< heroArray[i].gender << " "
<< endl;
}
}
int main()
{
int len = sizeof(heroArray) / sizeof(heroArray[0]);
cout << "排序前输出:" << endl;
printinfo(heroArray, len);
cout << endl;
bubbleSort(heroArray, len);
cout << "排序后输出:" << endl;
printinfo(heroArray, len);
system("pause");
return 0;
}
以上是关于2021-09-20黑马程序员结构体案例2实例的主要内容,如果未能解决你的问题,请参考以下文章
黑马程序员C语言基础(第八天)复合类型(自定义类型)共用体(联合体)枚举 typedef