刷算法题中遇到的这两个函数:
要注意的是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";
}
}