首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std库中的哪个函数可以二元搜索向量并找到一个元素?

在C++的<algorithm>库中,std::binary_search函数可以在一个已排序的向量中查找一个元素。这个函数使用二元搜索算法,它的时间复杂度是O(log n)。

函数原型:

代码语言:cpp
复制
bool binary_search(ForwardIt first, ForwardIt last, const T& value);

其中,firstlast是向量的迭代器,value是要查找的元素。

示例代码:

代码语言:cpp
复制
#include<iostream>
#include<vector>
#include<algorithm>

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    int target = 3;

    if (std::binary_search(vec.begin(), vec.end(), target)) {
        std::cout << "Found "<< target << " in the vector."<< std::endl;
    } else {
        std::cout << "Could not find "<< target << " in the vector."<< std::endl;
    }

    return 0;
}

输出:

代码语言:txt
复制
Found 3 in the vector.

需要注意的是,std::binary_search函数要求输入的向量是有序的。如果向量未排序,可以使用std::sort函数对其进行排序。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券