![]() |
#2
rjsp2022-12-09 19:58
for (;len>=1;len--) { for (int start=1;start<len;start++) 假如在你源码上改 ![]() #include <iostream> #include <string> using namespace std; struct Hero { std::string name; int age; std::string sex; }; void bubble_sort( struct Hero heroArray[], size_t len ) { for( size_t i=len; i!=0; --i ) { for( size_t j=1; j!=len; ++j ) { if( heroArray[j-1].age > heroArray[j].age ) { std::swap( heroArray[j-1].name, heroArray[j].name ); std::swap( heroArray[j-1].age, heroArray[j].age ); std::swap( heroArray[j-1].sex, heroArray[j].sex ); } } } } void print_array( const struct Hero heroArray[], size_t len ) { for( size_t i=0; i!=len; ++i ) { cout << heroArray[i].name << '\n'; } } int main( void ) { struct Hero heroArray[5]= { {"刘备",23,"男"}, {"关羽",100,"男"}, {"张飞",20,"男"}, {"赵云",150,"男"}, {"貂蝉",88,"女"} }; size_t len = sizeof(heroArray)/sizeof(heroArray[0]); bubble_sort( heroArray, len ); print_array( heroArray, len ); return 0; } 假如用C++正正经经地写 ![]() #include <string> struct Hero { std::string name; int age; std::string sex; }; #include <iostream> #include <algorithm> using namespace std; int main( void ) { struct Hero heros[] = { {"刘备", 23, "男"} , {"关羽", 100, "男"} , {"张飞", 20, "男"} , {"赵云", 150, "男"} , {"貂蝉", 88, "女"} }; sort( begin(heros), end(heros), [](const auto& a,const auto& b){return a.age<b.age;} ); for( const auto& e : heros ) cout << e.name << '\n'; } |
#include "touwenjian.h"
struct Hero
{
string name;
int age;
string sex;
};
//冒泡排序,将年龄大的排到后面
void bubblesort(struct Hero heroArray[], int len)
{
for (int len=0;len>=1;len--)
{
for (int start=1;start<=len;start++)
{
if (heroArray[start-1].age>heroArray[start].age)
{
struct Hero tmp=heroArray[start];
heroArray[start]=heroArray[start-1];
heroArray[start-1]=tmp;
}
}
}
}
//打印排序后的英雄名字
void printArray(struct Hero heroArray[],int len)
{
for (int i=0;i<len;i++)
{
cout<<heroArray[i].name;
}
}
int main()
{
//5个英雄结构体
struct Hero heroArray[5]=
{
{"刘备",23,"男"},
{"关羽",100,"男"},
{"张飞",20,"男"},
{"赵云",150,"男"},
{"貂蝉",88,"女"}
};
int len=sizeof(heroArray)/sizeof(heroArray[0]);
//调用函数
bubblesort(heroArray,len);
printArray(heroArray,len);
system("pause");
return 0;
}