STL基础入门08_最值

本文介绍如何使用C++标准库中的min_element和max_element函数来查找向量中的最小和最大元素,并通过一个示例展示了如何自定义比较函数以实现基于绝对值大小的排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <cmath>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;

//fabs针对浮点数,abs针对整数
//b表示起始的迭代器,e表示终止的迭代器,函数返回的是迭代器 


/*
1.min_element(b, e)		

2.min_element(b, e, op)

3.max_element(b, e)

4.max_element(b, e, op)
*/ 
bool abs_more(int x,int y)	//整数按绝对值从小到大排序 
{
	return abs(x)<=abs(y);
}
int main()
{
	
	int a[6]={-15,23,80,38,3,-99};
	vector<int> vec(a,a+6);
	cout<<*min_element(vec.begin(),vec.end())<<endl;
	cout<<*max_element(vec.begin(),vec.end())<<endl;
	
	cout<<*max_element(vec.begin(),vec.end(),abs_more)<<endl;
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值