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

题目

设计一个分数类 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

cpp 复制代码
#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;
}
相关推荐
clint4561 天前
C++进阶(1)——前景提要
c++
夜悊2 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴2 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0012 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾2 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you2 天前
constexpr函数
c++
凡人叶枫2 天前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
凡人叶枫2 天前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss2 天前
BRpc使用
c++·rpc
-森屿安年-2 天前
63. 不同路径 II
c++·算法·动态规划