功能描述:

    • 查找指定元素是否存在

    函数原型:

    • bool binary_search(iterator beg, iterator end, value);

    //查找指定元素,查到返回true 否则false
    //注意:无序序列中不可用
    //beg起始迭代器
    //end结束迭代器
    //value查找元素

    代码演示:

    1. #include<iostream>
    2. using namespace std;
    3. #include<algorithm>
    4. #include<vector>
    5. //常用查找算法 binary_search
    6. void test01() {
    7. vector<int>a;
    8. for (int i = 0; i < 10; i++) {
    9. a.push_back(i);
    10. }
    11. //查找容器中是否有元素9
    12. //注意:容器必须是有序的序列(底层原理是二分查找)
    13. //如果是无序的,结果未知。
    14. bool ret = binary_search(a.begin(), a.end(), 9);
    15. if (ret) {
    16. cout << "找到该元素" << endl;
    17. }
    18. else {
    19. cout << "未找到该元素" << endl;
    20. }
    21. }
    22. int main() {
    23. test01();
    24. return 0;
    25. }

    运行结果:
    image.png