c++ stl二分查找与lower_bound
2021/6/2 20:51:16
本文主要是介绍c++ stl二分查找与lower_bound,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
- binary_search实现
int myBinary_search(int arr[], int n, int target) { int first = 0, last = n; int mid; while (first < last) { mid = first + (last - first) / 2; if (arr[mid] == target) { return mid; } else if ( target > arr[mid] ) { first = ++mid; } else { last = mid; } } return -1; } void test() { int arr[] = { 5,7,7,8,8,10 }; cout << myBinary_search(arr, 6, 1) << endl; //-1 cout << myBinary_search(arr, 6, 5) << endl; //0 cout << myBinary_search(arr, 6, 8) << endl; //3 cout << myBinary_search(arr, 6, 10) << endl;//5 }
- lower_bound实现
template<typename ForwardIter, typename T> ForwardIter myLower_bound(ForwardIter first, ForwardIter last, T value) { while (first != last) { auto mid = next(first, distance(first, last) / 2); if (value > *mid) first = ++mid; else last = mid; } return first; } template<typename ForwardIter, typename T> ForwardIter myUpper_bound(ForwardIter first, ForwardIter last, T value) { while (first != last) { auto mid = next(first, distance(first, last) / 2); if (value >= *mid) first = ++mid; else last = mid; } return first; }
- cppreference.com
//可能的实现 //版本一 template<class ForwardIt, class T> bool binary_search(ForwardIt first, ForwardIt last, const T& value) { first = std::lower_bound(first, last, value); return (!(first == last) && !(value < *first)); } //版本二 template<class ForwardIt, class T, class Compare> bool binary_search(ForwardIt first, ForwardIt last, const T& value, Compare comp) { first = std::lower_bound(first, last, value, comp); return (!(first == last) && !(comp(value, *first))); }
myBinary_search根据lower_bound实现
这篇关于c++ stl二分查找与lower_bound的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-01使用 SVN合并操作时,怎么解决冲突的情况?-icode9专业技术文章分享
- 2025-01-01告别Anaconda?试试这些替代品吧
- 2024-12-31自学记录鸿蒙API 13:实现人脸比对Core Vision Face Comparator
- 2024-12-31自学记录鸿蒙 API 13:骨骼点检测应用Core Vision Skeleton Detection
- 2024-12-31自学记录鸿蒙 API 13:实现人脸检测 Core Vision Face Detector
- 2024-12-31在C++中的双端队列是什么意思,跟消息队列有关系吗?-icode9专业技术文章分享
- 2024-12-31内存泄漏(Memory Leak)是什么,有哪些原因和优化办法?-icode9专业技术文章分享
- 2024-12-31计算机中的内存分配方式堆和栈有什么关系和特点?-icode9专业技术文章分享
- 2024-12-31QT布局器的具体使用原理和作用是什么?-icode9专业技术文章分享
- 2024-12-30用PydanticAI和Gemini 2.0构建Airflow的AI助手