在C++中,标准模板库(STL)提供了多种查找技术,包括二分查找和其他查找函数。以下是几个常用的查找技术及其用法:
1. 二分查找 (std::binary_search)
- std::binary_search 用于检查元素是否存在于已排序的容器中(注意 必须是已排序,否则返回的结果不可靠)
- ps:返回值是bool
- 时间复杂度是O(logn),如果是大规模无序数据,就先用sort,再用这个二分查找函数;
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 3, 4, 6, 8, 9, 11};
int target = 6;
if (std::binary_search(vec.begin(), vec.end(), target)) {
std::cout << "Element found" << std::endl;
} else {
std::cout << "Element not found" << std::endl;
}
return 0;
}
2. std::lower_bound 和 std::upper_bound
这些函数用于查找元素在已排序容器中的位置。
- std::lower_bound 返回不小于目标值的第一个元素的迭代器。(也就是第一个>=target的位置,迭代器相当于容器中的指针)
- std::upper_bound 返回大于目标值的第一个元素的迭代器。(返回>target的位置)
- 注意下面代码中使用lower来查找元素是否存在!
- 注意,在获得迭代器以后,查看index一定要减去v.begin()
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 3, 4, 6, 8, 9, 11};
int target = 6;
auto lower = std::lower_bound(vec.begin(), vec.end(), target);
auto upper = std::upper_bound(vec.begin(), vec.end(), target);
if (lower != vec.end() && *lower == target) {
std::cout << "Lower bound found at index: " << (lower - vec.begin()) << std::endl;
} else {
std::cout << "Lower bound not found" << std::endl;
}
if (upper != vec.end()) {
std::cout << "Upper bound found at index: " << (upper - vec.begin()) << std::endl;
} else {
std::cout << "Upper bound not found" << std::endl;
}
return 0;
}
3. std::find
- std::find 用于在容器中查找第一个等于目标值的元素,适用于无序和有序容器。
- 注意,好处是可以用于无序容器,但是时间复杂度是O(n),适用于小规模数据!
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 3, 4, 6, 8, 9, 11};
int target = 6;
auto it = std::find(vec.begin(), vec.end(), target);
if (it != vec.end()) {
std::cout << "Element found at index: " << (it - vec.begin()) << std::endl;
} else {
std::cout << "Element not found" << std::endl;
}
return 0;
}
4. std::find_if
std::find_if 根据给定的条件查找第一个满足条件的元素。
#include <iostream>
#include <vector>
#include <algorithm>
// 定义一个普通函数来检查是否为偶数
bool is_even(int x) {
return x % 2 == 0;
}
int main() {
std::vector<int> vec = {1, 3, 4, 6, 8, 9, 11};
// 使用 std::find_if 查找向量中第一个满足 is_even 条件的元素
auto it = std::find_if(vec.begin(), vec.end(), is_even);
if (it != vec.end()) {
std::cout << "First even element found at index: " << (it - vec.begin()) << std::endl;
} else {
std::cout << "No even element found" << std::endl;
}
return 0;
}