C++中非递减向量的上界和下界
本文将讨论在 C++ STL 中对非递减排序数组使用 vector::upper_bound() 和 vector::lower_bound()。
向量类似于动态数组;当向其中插入或删除值时,它能够自行修改其大小。
在向量中,下界返回一个指向范围内第一个不小于给定值的元素的迭代器。上界返回一个指向范围内第一个大于给定值的元素的迭代器。
输入
30 30 30 20 20 20 10 10
输出
Lower bound of 20= 3 Upper bound of 20= 6
输入
9 9 8 8 8 7 7 7 6 6 6 6
输出
Lower bound of 7= 5 Upper bound of 7= 8
返回值
它返回一个指向范围的第一个元素的迭代器,以及一个指向范围的最后一个元素的迭代器。
可采用的方法
首先,我们初始化向量。
然后我们以非递减顺序对向量元素进行排序。
然后我们找到它的下界。
然后我们找到它的上界。
最后我们打印两个界限。
使用上述方法,我们可以找到任何向量的下界和上界,必须对向量进行排序才能找到其下界和上界。如果向量未排序,则无法找到其界限。
示例
/ / C++ program to demonstrate the working of lower bound and upper bound
#include<iosteam.h>
#include<vector.h>
Using namespace std;
int main ( ){
int vect[ ] = {13,13,13,16,16,16,17,17,17,17,18,18}
vector<int> v(vect, vect+8);
sort (v.begin( ), v.end( ), greater<int>( ));
cout<< “ \n Sorted Vector: ”;
for( auto i = vect.begin( ), i =! vect.end( ), ++i)
vector<int> iterator low, up;
low = lower_bound (v.begin( ), v.end( ), 17);
up = upper_bound (v.begin( ), v.end( ), 17);
cout<<” Lower bound” << (lower – v.begin( ))<< “ \n”;
cout<< “ Upper bound “<< (upper – v,begin( ))<<”\n”;
return 0;
}输出
如果我们运行上述代码,它将生成以下输出
Sorted Vector: 18 18 17 17 17 17 16 16 16 13 13 13 Lower bound = 2 Upper bound = 6
示例
#include<iosteam.h>
#include<vector.h>
Using namespace std;
int main ( ){
int vect[ ] = {5,5,5,5,7,7 7,8,8,8,8,9,9,9,10,10}
vector<int> v(vect, vect+16);
sort (v.begin( ), v.end( ));
cout<< “ \n Sorted Vector: ”;
for( auto i = vect.begin( ), i =!vect.end( ), ++i)
vector<int> iterator low, up;
low = lower_bound (v.begin( ), v.end( ), 8);
up = upper_bound (v.begin( ), v.end( ), 8);
cout<<” Lower bound” << (lower – v.begin( ))<< “ \n”;
cout<< “ Upper bound “<< (upper – v,begin( ))<<”\n”;
return 0;
}输出
如果我们运行上述代码,它将生成以下输出
Sorted Vector: 10 10 9 9 9 8 8 8 8 7 7 7 5 5 5 5 Lower bound = 5 Upper bound = 9
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP