【C++】一个求数组中最大元素的函数模板

本文介绍了如何在C++中设计一个Fraction类,包含分子和分母属性,以及重载运算符。同时,展示了如何使用Max_element函数模板求解Fraction数组中的最大分数元素。
摘要由CSDN通过智能技术生成

题目

设计一个分数类 F r a c t i o n Fraction Fraction,再设计一个名为 M a x e l e m e n t Max_element Maxelement 的函数模板,能够求数组中最大的元素,并用该模板求一个 F r a c t i o n Fraction Fraction 数组中的最大元素。


C o d e Code Code

#include <bits/stdc++.h>
using namespace std;

template<class T>
T Max_element(T a[], int len) {
	T maxn = a[0];
	for (int i = 1; i < len; i ++) {
		if (a[i] > maxn) {
			maxn = a[i];
		}
	}
	return maxn;
}

class Fraction{
	int numerator; // 分子
	int denominator; // 分母
public:
	Fraction(int n, int d):numerator(n), denominator(d){
		if (denominator < 0) { // 确保分母为正
			denominator *= -1;
			numerator *= -1;
		}
	}
	bool operator> (const Fraction& f)const{
		return numerator * f.denominator > f.numerator * denominator;
	}
	bool operator== (const Fraction& f)const{
		return numerator * f.denominator == f.numerator * denominator;
	}
	friend ostream& operator<< (ostream& o, const Fraction& f);
};

// 重载<<使得分数对象可以通过cout输出
ostream& operator<< (ostream& os, const Fraction& f) {
	os << f.numerator << "/" << f.denominator;
	return os;
}
/*
  这里的os引用的是主函数中的cout,返回os是为了实现<<的连续使用。
  参数os只能是ostream的引用,而不能是ostream的对象,
  因为ostream的复制构造函数是私有的,不能生成ostream参数对象。
 */

int main() {
	int a[5] = {1, 5, 2, 3, 4};
	Fraction f[4] = {Fraction(8, 6), Fraction(-8, 4), Fraction(3, 2), Fraction(5, 6)};
	cout << Max_element(a, 5) << "\n";
	cout << Max_element(f, 4) << "\n";
	
	return 0;
}
  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值