【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;
}
相关推荐
感哥9 小时前
C++ 多态
c++
沐怡旸16 小时前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River41619 小时前
Javer 学 c++(十三):引用篇
c++·后端
感哥21 小时前
C++ std::set
c++
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
博笙困了1 天前
AcWing学习——差分
c++·算法
青草地溪水旁1 天前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(2)
c++·设计模式·抽象工厂模式
青草地溪水旁1 天前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(1)
c++·设计模式·抽象工厂模式
感哥1 天前
C++ std::vector
c++
zl_dfq1 天前
C++ 之【C++11的简介】(可变参数模板、lambda表达式、function\bind包装器)
c++