MOOC清华《面向对象程序设计》第3章编程题第2题:重载下标运算符以统计分段人数

为了统计全年级学生考试成绩的分数段分布情况,即1~10、11~20、21~30、...、91~100等各个分数段的学生人数,拟设计实现一个重载了下标运算符的类,该类对象使用元素为考试成绩的数组和数组元素个数来初始化,当使用0~9的整数下标k来访问该对象时,返回 第k分数段(10*k + 1 <= e <= 10*k + 10)中的元素个数。(本题不计入总成绩) 提交要求:请将各个源文件(*.h, *.cpp)合并打印到一个PDF文件上传,要求各文件首行用注释说明文件名称。建议源代码中加上必要的注释,以便阅读。


//main.cpp
#include <iostream>
#include "Test.h"
using namespace std;

int main() {
	int array[50] = {98,99,56,53,78,  89,87,86,43,24,  
					25,67,77,78,79,  65,53,87,24,95,  
					79,76,77,79,80,  88,87,86,80,87,
					96,96,100,76,76,  90,98,97,99,92,
					87,89,91,93,95,  98,86,43,7,32};
	Test obj(array, 50);
	cout << "obj[9] = " << obj[9] << endl << endl;
	return 0;
}

//Test.h
#ifndef Test_h
#define Test_h

class Test{
private:
	int N;
	int array[1000];
	int temp[10];
	int count;
public:
	Test(int* src, int N);
	~Test();
	
	int& operator[] (const int n);
};

#endif

//Test.cpp
#include <iostream>
#include "Test.h"
using namespace std;

Test::Test(int* src, int n) {
		N = n;
		for(int i = 0; i < N; i++)
			array[i] = src[i];
	}
	
Test::~Test(){
	cout << "析构函数已调用!" << endl;
}

int& Test::operator[] (const int k){
	void QuickSort(int* array, int start, int end); 
	void OutputOfArray(int* array, int n); 
	QuickSort(array, 0, N);
	OutputOfArray(array, N);
	int tmp_1 = 10 * k + 1, tmp_2 = 10 * k + 10;
	count = 0;
	for(int i = 0; i < N; i++){
		if((array[i] <= tmp_2)&&(array[i] >= tmp_1))
			count++;
		if(array[i] < tmp_1) break;
	}
	return count;
}

void QuickSort(int* array, int start, int end)    
{    
    if(start >= end - 1)     
        return;      
        
    int left = start, right = end;      
    
    int pivot = array[left];    
    int temp = 0.0;    
        
    for(int i = left + 1; i < right;   )      
    {    
        if(array[i] > array[left])    
        {    
            temp = array[left];    
            array[left] = array[i];    
            array[i] = temp;    
            left++;    
            i++;    
        }    
        else    
        {    
            temp = array[i];    
            for(int j = i; j < right; j++)    
                array[j] = array[j + 1];        
            array[right - 1] = temp;      
            right--;     
        }    
    }    
    array[left] = pivot;    
    
    QuickSort(array, start, left);    
    QuickSort(array, left + 1, end);    
}  

void OutputOfArray(int* array, int n)      
{      
    for(int i = 0; i < n; i++)      
        cout << array[i] << '\t';  
    cout << endl;      
}    

测试结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值