C++算法lower_bound()、max()、max_element()、min()、min_element()

lower_bound() 下限

_FwdIt lower_bound(_FwdIt _First, _FwdIt _Last, const _Ty& _Val)


返回值:_Fwdlt 一个迭代器
参数1:容器开头
参数2:容器结尾
参数3:查找的值
作用:查找第一个大于等于_Val的值

	//输出arr
	void showarr(vector<int> &Arr)
	{
		vector<int>::iterator iteArr = Arr.begin();
		for (iteArr ; iteArr != Arr.end(); iteArr++)
		{
			cout << *iteArr << "\t";
		}
		cout << endl;
	}

	void main()
	{
		vector<int> arr = { 1,2,1,4,3 };
		showArr(arr);
	
		vector<int>::iterator ite,ite2;
		int i = 0;
		//_FwdIt lower_bound(_FwdIt _First, _FwdIt _Last, const _Ty& _Val)
		ite = lower_bound(arr.begin(), arr.end(), 3);
	
		for (ite2 = arr.begin(); ite2 <= ite; ite2++)
		{
			++i;
		}
		cout << "第一次遇见>=3的数据位置为:" << i << endl; //返回 4
	}

最大与最小

1.max() 最大值

_CONST_FUN const _Ty& (max)(const _Ty& _Left, const _Ty& _Right)


返回值: _Ty,传递的参数是什么类型它就什么类型
参数1:左值
参数2:右值
作用:返回两个值中最大的值。

vector<int> arr = { 1,2,1,4,3 };
showArr(arr);

int a = max(*(arr.begin()),*(arr.end()-1));

cout << a << endl;	//返回 3

_CONST_FUN const _Ty& (max)(const _Ty& _Left, const _Ty& _Right, _Pr _Pred)


返回值:_Ty,传递的参数是什么类型它就什么类型
参数1:左值
参数2:右值
参数3:仿函数
作用:通过仿函数里的方法进行比较。

vector<int> arr = { 1,2,1,4,3 };
showArr(arr);

//仿函数为什么要返回bool呢!原因在该函数它的返回值中
//return (_DEBUG_LT_PRED(_Pred, _Left, _Right) ? _Right : _Left);

//_DEBUG_LT_PRED(_Pred, _Left, _Right) 这个是bool ,
//当为true时返回_Right,false时返回_Left

int a = max(*(arr.begin()), *(arr.end() - 1),
	[](int left, int right) {
		bool a = true;
		if (left < right)
		{
			a = false;
		}
		return a;
	});

cout << a << endl;	//返回 1

2.max_element() 最大值出现的位置

_FwdIt max_element(_FwdIt _First, _FwdIt _Last)


返回值:_FwdIt 一个迭代器
参数1:迭代器,容器开头
参数2:迭代器,容器结尾
作用:返回最大值出现的位置迭代器

vector<int> arr = { 1,5,1,4,3 };
showArr(arr);

vector<int>::iterator ite,ite2;
ite = max_element(arr.begin(), arr.end());

int i = 0;
for (ite2 = arr.begin(); ite2 <= ite; ++ite2)
{
	++i;
}
cout << "最大值的位置为:" << i << endl;	//2

3.min() 最小值

_CONST_FUN const _Ty& (min)(const _Ty& _Left, const _Ty& _Right)


返回值:_Ty,传递的参数是什么类型它就什么类型
参数1:左值
参数2:右值
作用:返回两值中最小的值。

vector<int> arr = { 1,5,1,4,3 };
showArr(arr);

int a = min(*(arr.begin()), *(arr.end() - 1));

cout << a << endl;	//返回 1

4.min_element() 最小值出现的位置

_FwdIt min_element(_FwdIt _First, _FwdIt _Last)


返回值:_FwdIt 一个迭代器
参数1:迭代器,容器开头
参数2:迭代器,容器结尾
作用:返回最小值出现的位置迭代器

vector<int> arr = { 1,5,0,4,3 };
showArr(arr);

vector<int>::iterator ite,ite2;
ite = min_element(arr.begin(), arr.end());

int i = 0;
for (ite2 = arr.begin(); ite2 <= ite; ++ite2)
{
	++i;
}
cout << "最大值的位置为:" << i << endl;	//3
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值