用函数重载的方式编写程序,统计出一个以给定结构为基准的结构体数组中名字/年龄/班级/性别为X的出现了多少次

有以下结构:

struct student{ 
	char name[32]; 
	int age; 
	int class; 
	bool sex; 
}; 

写出函数,用函数重载的方式编写程序,统计出一个以上述结构为基准的结构体数组中:
1、名字为X的出现了多少次
2、年龄为X的出现了多少次
3、班级为X的出现了多少次
4、性别的X的出现了多少次

#include <iostream>

using namespace std;

struct Student
{
	char m_name[32];
	int m_age;
	int m_classid;
	bool m_sex;
};

bool cmpEql(Student a, Student b)
{
	return a.m_age == b.m_age;
}

int CountNumber(Student * st, int n, Student val, bool (*cmp)(Student, Student) = cmpEql)
{
	int i;
	int count = 0;

	for (i = 0; i < n; ++i)
	{
		if (cmp(st[i], val))
		{
			count++;
		}
	}
	
	return count;
}

bool cmpEqlName(Student a, Student b)
{
	return strcmp(a.m_name, b.m_name) ? false : true;
}

bool cmpEqlSex(Student a, Student b)
{
	return !(a.m_sex ^ b.m_sex);//给定结构体中定义的m_sex为bool型,比较式性别相同即return 1, 否则为0
}

bool cmpEqlClassid(Student a, Student b)
{
	return a.m_classid == b.m_classid;
}

int main()
{
	Student s[] = { {"xiaoming", 18, 1, true},
	                { "Mary", 20, 2, false }, 
	                {"Jack", 20, 2, true},
	                {"Allen", 30, 1, true},
	                {"Curry", 31, 2, true},
	                {"Red", 18, 1, false} 
	};

	Student test = { "xiaoming", 18, 1, true };

	cout << CountNumber(s, 6, test, cmpEqlClassid) << endl;
	cout << CountNumber(s, 6, test, cmpEqlName) << endl;
	cout << CountNumber(s, 6, test, cmpEqlSex) << endl;
	cout << CountNumber(s, 6, test) << endl;//比较规则为缺省参数,不传默认比较年龄

	system("pause");
	return 0;
}
发布了235 篇原创文章 · 获赞 28 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_44781107/article/details/103353903