【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;
}
相关推荐
无忧.芙桃5 小时前
C++语言原理与实践(二十三):哈希表的实现
c++·链表·哈希算法·散列表·哈希表
AvocadoZeroOneOI8 小时前
B4500 [GESP202603 三级] 凯撒密码 详细解题报告
c++·算法
whitelbwwww10 小时前
cuBLAS--CUDA高性能线性代数计算库--第一部分
c++·线性代数·gpu算力·cuda c++
eggwyw12 小时前
C++设计模式之解释器模式
开发语言·c++
我不会插花弄玉1 天前
13.多路转接epoll【由浅入深-网络】
网络·c++·epoll
郝学胜-神的一滴1 天前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
西西弗Sisyphus1 天前
C++ explicit 关键字工程实践
开发语言·c++
AIgorithmGEEK1 天前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
一拳一个呆瓜1 天前
【STL】头文件:<cmath>
c++·stl
草莓熊Lotso1 天前
【C++ 基于微服务的即时通讯系统】ElasticSearch 用户数据管理实现
linux·数据库·c++·elasticsearch·微服务·架构