【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;
}
相关推荐
喵了几个咪2 分钟前
C++ IDE:最适合 C++ 初学者的 IDE 是什么?
开发语言·c++·ide
2501_9418024825 分钟前
C++高性能并发编程实战:从多线程管理到内存优化与任务调度全流程解析
java·开发语言·c++
zzzsde29 分钟前
【C++】哈希表实现
数据结构·c++·哈希算法·散列表
Elias不吃糖1 小时前
C++ 中“编译器自动帮我传参”和“我自己写初始化”的本质区别
c++
阿巴~阿巴~1 小时前
TCP服务器实现全流程解析(简易回声服务端):从套接字创建到请求处理
linux·服务器·网络·c++·tcp·socket网络编程
Elias不吃糖1 小时前
LeetCode每日一练(189, 122)
c++·算法·leetcode
赖small强1 小时前
【Linux C/C++开发】第20章:进程间通信理论
linux·c语言·c++·进程间通信
赖small强1 小时前
【Linux C/C++开发】第24章:现代C++特性(C++17/20)核心概念
linux·c语言·c++·c++17/20
-森屿安年-2 小时前
LeetCode 11. 盛最多水的容器
开发语言·c++·算法·leetcode
ouliten2 小时前
C++笔记:std::stringbuf
开发语言·c++·笔记