upper_bound()返回值

来源:互联网 发布:闵玧其知乎 编辑:程序博客网 时间:2024/05/22 16:23

函数upper_bound()返回的在前闭后开区间查找的关键字的上界,如一个数组number序列1,2,2,4.upper_bound(2)后,返回的位置是3(下标)也就是4所在的位置,同样,如果插入元素大于数组中全部元素,返回的是last。(注意:此时数组下标越界!!)

返回查找元素的最后一个可安插位置,也就是“元素值>查找值”的第一个元素的位置


测试代码如下:

#include <iostream>#include <algorithm>#include <functional>#include <vector>using namespace std;void main(){    const int VECTOR_SIZE = 8 ;    // Define a template class vector of int    typedef vector<int, allocator<int> > IntVector ;    //Define an iterator for template class vector of strings    typedef IntVector::iterator IntVectorIt ;    IntVector Numbers(VECTOR_SIZE) ;    IntVectorIt start, end, it, location, location1;    // Initialize vector Numbers    Numbers[0] = 4 ;    Numbers[1] = 10;    Numbers[2] = 10 ;    Numbers[3] = 30 ;    Numbers[4] = 69 ;    Numbers[5] = 70 ;    Numbers[6] = 96 ;    Numbers[7] = 100;    start = Numbers.begin() ;   // location of first                                // element of Numbers    end = Numbers.end() ;       // one past the location                                // last element of Numbers    // print content of Numbers    cout << "Numbers { " ;    for(it = start; it != end; it++)        cout << *it << " " ;    cout << " }\n" << endl ;    //return the last location at which 10 can be inserted    // in Numbers    location = lower_bound(start, end, 9) ;location1 = upper_bound(start, end, 10) ;    cout << "Element 10 can be inserted at index "        << location - start<< endl ; cout << "Element 10 can be inserted at index "        << location1 - start<< endl ;}


原创粉丝点击