我需要c++stl库二分函数的例子
时间: 2023-06-07 08:10:36 浏览: 57
好的,以下是一个使用C++ STL库的二分查找函数的示例代码:
```
#include <iostream>
#include <algorithm> //包含STL库头文件
using namespace std;
int main()
{
int a[] = {1, 2, 3, 4, 5}; //定义一个已排序数组
int n = sizeof(a) / sizeof(a[0]); //计算数组大小
int find_num = 3; //需要查找的数字
//使用二分查找函数进行查找
bool result = binary_search(a, a + n, find_num);
//输出结果
if (result)
cout << "找到了 " << find_num << endl;
else
cout << "没找到 " << find_num << endl;
return 0;
}
```
以上代码演示了如何使用STL库中的`binary_search`函数进行二分查找。要注意的是,使用该函数的前提是已经将数组进行了排序。
相关问题
c++stl二分查找
C++ STL实现二分查找的函数有三个:lower_bound、upper_bound和binary_search。
lower_bound函数用来查找第一个不小于给定值的元素,如果存在多个相同的元素,则返回第一个出现的位置。
upper_bound函数用来查找第一个大于给定值的元素,如果存在多个相同的元素,则返回第一个大于给定值的位置。
binary_search函数用来判断给定值是否在有序容器中出现,如果存在则返回true,否则返回false。
在给出的代码中,使用了lower_bound函数来查找数组a中是否存在与b相等的元素,如果存在,则将其赋值给ans变量。
需要注意的是,使用这些函数前需要先对容器进行排序,以保证二分查找的正确性。可以使用algorithm头文件中的sort函数对容器进行排序。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [STL之二分查找](https://blog.csdn.net/jfkidear/article/details/100171041)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *3* [C++ STL中的 二分查找](https://blog.csdn.net/shuaizhijun/article/details/88982556)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
C++ STL 二分查找
以下是C++ STL中使用二分查找的示例代码:
```cpp
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> haystack {1, 3, 4, 5, 9};
std::vector<int> needles {1, 2, 3};
for (auto needle : needles) {
std::cout << "Searching for " << needle << '\n';
if (std::binary_search(haystack.begin(), haystack.end(), needle)) {
std::cout << "Found " << needle << '\n';
} else {
std::cout << "no dice!\n";
}
}
}
```
这段代码使用了`std::binary_search`函数来进行二分查找。它接受一个有序范围(在本例中是`haystack`向量)和一个要查找的值(在本例中是`needle`)。如果找到了该值,则返回`true`,否则返回`false`。
在上述代码中,我们使用了一个循环来遍历`needles`向量中的每个元素,并对每个元素进行二分查找。如果找到了该元素,则输出"Found",否则输出"no dice!"。