二分法
简介
二分法在c++中相关的函数是: (需要要求序列已排好序)
binary_search(begin,end,val); 查找序列中等于val的值,有返回true,没有返回false
lower_bound(begin,end,val); 查找序列中大于等于val的值,有返回该元素迭代器,没有返回end
upper_bound(begin,end,val); 查找序列中严格大于val的值,有返回该元素迭代器,没有返回end
它们包含在头文件中
实例
-----------------基本数据类型---------------
void main() {
vector<int> arr = { 5,6,2,9,1 };
sort(arr.begin(), arr.end()); //1,2,5,6,9
bool is_exist = binary_search(arr.begin(), arr.end(), 4);
auto res_lower = lower_bound(arr.begin(), arr.end(), 2);
auto res_upper = upper_bound(arr.begin(), arr.end(), 2);
cout << is_exist << endl; //0
cout << *res_lower << endl; //2
cout << *res_upper << endl; //5
}
--------------自定义数据类型---------------
class student {
friend ostream& operator<<(ostream& out, student& s);
public:
int math;
int english;
student(int math, int english) {
this->math = math;
this->english = english;
}
bool operator==(const student& s1) {
if (this->math == s1.math && this->english == s1.english) return true;
return false;
}
};
ostream& operator<<(ostream& out, student& s) {
out << "math:" << s.math << endl;
out << "english:" << s.english << endl;
return out;
}
class myCompare_find {
public:
bool operator()(student s1, student s2) {
return s1.math < s2.math;
}
};
class myCompare_sort {
public:
bool operator()(student s1, student s2) {
return s1.math < s2.math;
}
};
void main() {
student s1(45, 50), s2(55, 56), s3(23, 100);
student s4(23, 10000);
vector<student> v = { s1,s2,s3 };
sort(v.begin(), v.end(),myCompare_sort()); //s3 s1 s2
cout << v[0];
bool is_exist = binary_search(v.begin(), v.end(), s4,myCompare_find()); // true
auto res_lower_bound = lower_bound(v.begin(), v.end(), s4, myCompare_find()); // s3
auto res_upper_bound = upper_bound(v.begin(), v.end(), s4, myCompare_find());// s1
cout << is_exist << endl;
cout << *res_lower_bound << endl;
cout << *res_upper_bound << endl;
}