面向对象程序设计2018上机题(2)

/*根据下列要求,编写完整程序。

设计一个类,用于对10元整型数组进行管理。要求:

(1)在定义对象时,能够为数组元素清0.

(2)定义成员函数input, 用于为数组元素输入数据。

(3)定义成员函数disp,用于显示数组的每个元素值。

(4)定义成员函数max,用于找出数组元素的最大值及其个数,其中最大值由函数值返回,个数由参数带回。

(5)定义成员函数find,用于找出数组中重复次数最多的数及其个数(可能存在多个),并显示出来。

(6)定义main函数,合理地调用上述每个函数。*/
#include <iostream>
#include <map>
#include <Windows.h>

#define NUM 10
using namespace std;

class Class
{
private:
	int* p;
public:
	Class();
	void input();
	void disp();
	int max_num(int &num);
	void find();
	~Class();
};

Class::Class()
{
	p = new int[NUM];
	for (int i = 0; i < NUM; i++) {
		p[i] = 0;
	}
}
Class::~Class()
{
	delete []p;
}
void Class::input()
{
	cout << "Please input  " << NUM << "numbers :" << endl;
	for (int i = 0; i < NUM; i++) {
		cin >> p[i];
	}
}
void Class::disp()
{
	cout << "当前数组为:" << endl;
	for (int i = 0; i < NUM; i++) {
		cout << p[i] << '\t';
	}
	cout << endl;
}
int Class::max_num(int &num)
{
	int max_number = 0;
	int n = 0;
	for (int i = 0; i < NUM; i++) {
		if (max_number < p[i]) {
			max_number = p[i];
			n = 1;
		}
		else if (max_number == p[i]) {
			n++;
		}
	}
	num = n;
	return max_number;
}
void Class::find()
{
	int max_times = 0;
	map<int, int>M;//C++关联式容器
	for (int i = 0; i < NUM; i++) {
		M[p[i]]++;
		if (M[p[i]] > max_times) {
			max_times = M[p[i]];
		} 
	}
	cout << "最大重复次数为:" << max_times << endl << "重复次数最多的数为:";
	map<int, int>::iterator it;
	for (it = M.begin(); it != M.end(); it++) {
		if (it->second == max_times) {
			cout << it->first << '\t';
		}
	}
}

int main()
{
	Class c;
	c.input();
	int max_number = 0;
	int n = 0;//最大值的个数
	max_number = c.max_num(n);
	cout << "最大值:" << max_number << '\t' << "最大值个数:" << n << endl;
	c.find();
	system("pause");
	return 0;
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值