学习

1、C和C++中struct不同:

C中struct结构体中是不能声明函数,而C++中的结构体是可以声明函数的。

2、struct和class的不同:

结构体默认情况下成员是public,而在class中成员默认的是private。

3、qsort函数

1)声明

void qsort(void *base,size_t num,size_t width,int (*fcmp)(const void *,const void *));

2)参数说明

base:待排序的数组

num:数组个数

width:单个元素所占的大小

fcmp:指向比较函数的函数指针(自己实现)

4、setw(n)

1)用到的头文件是#include <iomanip>

2)函数说明:设置输出字符宽度,n表示相应的值,默认是右对齐,可以使用cout.setf(ios::left);这种方式设置输出为左对齐。

5、练习代码:

示例说明:利用快排方式来排序球队名词,首先是按照球队的积分高低排名,积分相同的则按照净胜球排名,净胜球相同按照进球数排名,如果净胜球也还相同的话,按照球队名称排序。


</pre><pre name="code" class="cpp">#include <iostream>
#include <iomanip>				//头文件是用setw用的
using namespace std;

struct FootballTeam
{
	char TeamName[20];			//队名
	int nPoint;				//积分
	int nAddBall;				//净胜球
	int nInBall;				//进球数
}Team[10];

int comp(const void* p1,const void* p2)
{
	FootballTeam * t1 = (FootballTeam*)p1;
	FootballTeam * t2 = (FootballTeam*)p2;
	int n1 = t1->nPoint - t2->nPoint;
	int n2 = t1->nAddBall - t2->nAddBall;
	int n3 = t1->nInBall - t2->nInBall;
	if(n1)
		return n1;
	else if(n2)
		return n2;
	else if(n3)
		return n3;
	else
		return strcmp(t1->TeamName,t2->TeamName);
}
int main()
{
	int nNum = 0;
	cout << "请输入球队数量:";
	cin >> nNum;
	cout << "输入球队积分信息:" <<endl;
	for (int i = 0;i <nNum;i++)
	{
		cin >>Team[i].TeamName >> Team[i].nPoint >>Team[i].nAddBall >>Team[i].nInBall;
	}
	qsort(Team,nNum,sizeof(FootballTeam),comp);
	cout << endl;
	cout.setf(ios::left);
	cout << setw(10) << "队名" << setw(10) << "积分" << setw(10) << "净胜球" << setw(10) << "进球数" << endl;
	for(int n = nNum - 1;n >= 0 ;n--)
	{
		cout.setf(ios::left);
		cout << setw(10) << Team[n].TeamName << setw(10) <<Team[n].nPoint << setw(10) << Team[n].nAddBall << setw(10) <<   Team[n].nInBall << endl;		
	}
	cout << endl;
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值