函數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 ;
}