c++ lower_bound fill() upper_bound 函数

刷算法题中遇到的这两个函数:

要注意的是lower_bound与upper_bound函数都是使用二分查找来实现的,且两个函数的返回值都是迭代器,也就是指针。

fill()函数用来填充一个容器的值,如一维数组,vector,二维数组,下面给出了这三种的填充方法。

lower_bound(起始地址,结束地址,要查找的数值) 返回的是数值 第一个 出现的位置。

upper_bound(起始地址,结束地址,要查找的数值) 返回的是数值 最后一个 出现的位置。

binary_search(起始地址,结束地址,要查找的数值) 返回的是是否存在这么一个数,是一个bool值。

1 函数lower_bound()

功能:函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置.

注意:如果所有元素都小于val,则返回last的位置,且last的位置是越界的!!

2 函数upper_bound()

功能:函数upper_bound()返回的在前闭后开区间查找的关键字的上界,返回大于val的第一个元素位置

注意:返回查找元素的最后一个可安插位置,也就是“元素值>查找值”的第一个元素的位置。同样,如果val大于数组中全部元素,返回的是last。(注意:数组下标越界)

一维数组的填充:

#include <iostream>     // std::cout
#include <algorithm>    // std::fill

using namespace std;

int main () {
  int array[8];                       // myvector: 0 0 0 0 0 0 0 0

  cout<<"=======begin======="<<"\n"; 
  for (int i = 0;i< 8;i++)
    cout << ' ' << array[i];
  cout << '\n'<<'\n';

  fill (array,array+4,5);   // myvector: 5 5 5 5 0 0 0 0
  fill (array+3,array+6,8);   // myvector: 5 5 5 8 8 8 0 0

  cout<<"=======after fill======="<<"\n"; 
  for (int i = 0;i< 8;i++)
    cout << ' ' << array[i];
  cout << '\n'<<'\n';
  
  return 0;
}

填充vector:

#include <iostream>     // std::cout
#include <algorithm>    // std::fill
#include <vector>       // std::vector

using namespace std;

int main () {
  vector<int> myvector (8);                       // myvector: 0 0 0 0 0 0 0 0

	cout<<"=======begin======="<<"\n"; 
  for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    cout << ' ' << *it;
  cout << '\n'<<'\n';

  fill (myvector.begin(),myvector.begin()+4,5);   // myvector: 5 5 5 5 0 0 0 0
  fill (myvector.begin()+3,myvector.end()-2,8);   // myvector: 5 5 5 8 8 8 0 0

  cout<<"=======after fill======="<<"\n"; 
  for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    cout << ' ' << *it;
  cout << '\n';
  
  return 0;
}

填充二维数组:

#include<cstdio>
#include<iostream>
using namespace std;

int main(){
	int G[6][4];
	fill(G[0],G[0]+6*4,520);
	for(int i = 0;i < 6;i++)
	{
		for(int j = 0;j < 4;j++){
			cout <<G[i][j] <<" ";
		}cout <<"\n";
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值