C++ 查找函数

1. lower_bound()

用于在指定区域内查找大于等于目标值的第一个元素(实质是二分法查找)

auto it = lower_bound(f.begin(), f.end(), num);

 

2. upper_bound() 

查找的是第一个大于目标值的元素

int *p = upper_bound(a, a + 5, 3);

 

3. equel_range()

用于在指定范围内查找等于目标值的所有元素,前提是已排好序

pair<int*, int*> range = equal_range(a, a + 9, 4);

 

4. find()

用于在指定范围内查找和目标元素值相等的第一个元素,找不到会到end()

std::vector<int>::iterator it;
it = find(myvector.begin(), myvector.end(), 30);
if (it != myvector.end())
    cout << "查找成功:" << *it;
else
    cout << "查找失败";
return 0;        

 

5. binary_search()

用于查找指定区域内是否包含某个目标元素,返回bool

bool hasElem = binary_search(a, a + 9, 4);

 

posted @ 2021-03-04 13:11  Kinghao0319  阅读(1213)  评论(0编辑  收藏  举报