C++ STL
函式原型
第一個版本(default):
template <class ForwardIterator, class T> ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val);
第二個版本(custom):
template <class ForwardIterator, class T, class Compare> ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val, Compare comp);
函式介紹
例如,有如下序列:
a[i]={12,15,17,19,20,22,23,26,29,35,40,51};
用值21調用lower_bound(),返回一個指向22的iterator。用值22調用lower_bound(),也返回一個指向22的iterator。第一個版本使用底層 < (小於)操作符,第二個版本根據comp進行排序和比較。
注意事項
調用lower_bound之前必須確定序列為有序序列,否則調用出錯。第一個版本排序根據底層的 <(小於)操作符,第二個版本根據comp進行排序。
舉例
第一個版本
vector<int>nums;nums.push_back(-242);nums.push_back(-1);nums.push_back(0);nums.push_back(5);nums.push_back(8);nums.push_back(8);nums.push_back(11);cout<<"Beforenumsis:";for(unsignedinti=0;i<nums.size();i++){cout<<nums[i]<<"";}cout<<endl;vector<int>::iteratorresult;int new_val=7;result=lower_bound(nums.begin(),nums.end(),new_val);nums.insert(result,new_val);cout<<"After,numsis:";for(unsignedinti=0;i<nums.size();i++){cout<<nums[i]<<"";}cout<<endl;
輸出:
Before nums is: -242 -1 0 5 8 8 11
After, nums is: -242 -1 0 5 7 8 8 11
第二個版本
#include<iostream>#include<vector>#include<algorithm>using namespace std;class person{private: int age;//年齡 double height;//身高 string name;//姓名public: person():age(0),height(0.0) {} person(const int age_, const double height_, const string &name_) :age(age_), height(height_), name(name_) {} int key1() const { return age; } double key2() const { return height; } const string &key3() const { return name; }};struct compareByTwoKey{ template<class T1,class T2> int operator()(const T1 &t1,const T2 &t2) { if(t1.key1()<t2.key1()) return true; else if(t1.key1()==t2.key1()) { if(t1.key2()<t2.key2()) return true; else return false; } else return false; }};void init_data(vector<person> &v){ v.push_back(person(12,96.8,"你好")); v.push_back(person(12,86.9,"你好")); v.push_back(person(13,76.8,"你好")); v.push_back(person(13,77.8,"你好")); v.push_back(person(10,70.8,"你好")); v.push_back(person(15,79.8,"你好")); v.push_back(person(18,176.8,"你好")); v.push_back(person(2,6.8,"你好")); v.push_back(person(12,55.8,"你好")); v.push_back(person(12,97.8,"hello")); sort(v.begin(),v.end(),compareByTwoKey());//一定要加上排序,並且排序函式跟lower_bound一致}int main(){ vector<person> v; init_data(v); personval(12,90.0,"hello"); vector<person>::iteratoriter iter=lower_bound(v.begin(),v.end(),val,compareByTwoKey());//跟sort函式一致 system("pause");}