upper_bound()返回值

来源:互联网 发布:c语言数字字符是什么 编辑:程序博客网 时间:2024/05/18 17:56

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

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

本文出处

测试代码如下:

[cpp] view plaincopy
  1. #include <iostream>  
  2. #include <algorithm>  
  3. #include <functional>  
  4. #include <vector>  
  5. using namespace std;  
  6.   
  7. void main()  
  8. {  
  9.     const int VECTOR_SIZE = 8 ;  
  10.   
  11.     // Define a template class vector of int  
  12.     typedef vector<int, allocator<int> > IntVector ;  
  13.   
  14.     //Define an iterator for template class vector of strings  
  15.     typedef IntVector::iterator IntVectorIt ;  
  16.   
  17.     IntVector Numbers(VECTOR_SIZE) ;  
  18.   
  19.     IntVectorIt start, end, it, location, location1;  
  20.   
  21.     // Initialize vector Numbers  
  22.     Numbers[0] = 4 ;  
  23.     Numbers[1] = 10;  
  24.     Numbers[2] = 10 ;  
  25.     Numbers[3] = 30 ;  
  26.     Numbers[4] = 69 ;  
  27.     Numbers[5] = 70 ;  
  28.     Numbers[6] = 96 ;  
  29.     Numbers[7] = 100;  
  30.   
  31.     start = Numbers.begin() ;   // location of first  
  32.                                 // element of Numbers  
  33.   
  34.     end = Numbers.end() ;       // one past the location  
  35.                                 // last element of Numbers  
  36.   
  37.     // print content of Numbers  
  38.     cout << "Numbers { " ;  
  39.     for(it = start; it != end; it++)  
  40.         cout << *it << " " ;  
  41.     cout << " }\n" << endl ;  
  42.   
  43.     //return the last location at which 10 can be inserted  
  44.     // in Numbers  
  45.     location = lower_bound(start, end, 9) ;  
  46.     location1 = upper_bound(start, end, 10) ;  
  47.   
  48.     cout << "Element 10 can be inserted at index "  
  49.         << location - start<< endl ;  
  50.      cout << "Element 10 can be inserted at index "  
  51.         << location1 - start<< endl ;  
  52. }  

0 0