C++中提供的所有关于查找的函数
std::find(begin(), end(), key)
std::find(begin(), end(), key)
:这个函数用于在一个范围内查找一个等于给定值的元素,返回一个指向该元素的迭代器,如果没有找到则返回范围的结束迭代器。
- 1.1 例如,如果我们有一个整数向量
std::vector<int> v = {1, 2, 3, 4, 5};
,我们用std::find查找3
std::vector<int> iter = std::find(v.begin(), v.end(), 3);
if(iter != v.end())
std::cout << *iter << std::endl;
std::count()
std::count()
:这个函数用于统计一个范围内等于给定值的元素的个数,返回一个整数。
- 2.1 例如,如果我们有一个字符数组
char s[] = "Hello, world!";
,计算l字符出现的次数,
我们可以用std::count(s, s + 13, 'l')
来统计数组中'l'的个数,返回3。
int countNum = std::count(s, s + 13, 'w');
std::cout << countNum << std::endl;
std::find_if()
std::find_if()
:这个函数用于在一个范围内查找一个满足给定谓词的元素,返回一个指向该元素的迭代器,如果没有找到则返回范围的结束迭代器。谓词是一个接受一个元素作为参数并返回一个布尔值的函数或函数对象。
- 3.1 例如,如果我们有一个字符串向量
std::vector<std::string> words = {"apple", "banana", "cherry", "date"};
,我们可以定义一个谓词函数bool is_longer_than_five(const std::string& s) { return s.size() > 5; }
,然后用std::find_if(words.begin(), words.end(), is_longer_than_five)
来查找第一个长度大于5的字符串,在这个例子中是"banana"。
std::vector<std::string> words = {"apple", "banana", "cherry", "date"};
std::find_if(words.begin(), words.end(), [](const std::string& s){ return s.size() > 5;});
std::any_if()
std::any_if()
:这个函数用于判断一个范围内是否存在一个满足给定谓词的元素,返回一个布尔值。谓词是同上。
- 4.1 例如,如果我们有一个浮点数数组
double a[] = {1.2, 3.4, 5.6, 7.8};
,我们可以定义一个谓词函数bool is_integer(double x) { return std::floor(x) == x; }
,然后用std::any_if(a, a + 4, is_integer)
来判断数组中是否有整数,在这个例子中是false。
double a[] = {1.2,3.4,5.6,7.8};
std::any_if(a, a+4, [](double x){std::floor(x) == x;});
std::binary_search()
std::binary_search()
:这个函数用于在一个已经排序的范围内查找一个等于给定值的元素,返回一个布尔值。如果范围没有排序,则结果是未定义的。
- 5.1 例如,如果我们有一个整数数组
int b[] = {2, 4, 6, 8, 10};
,我们可以用std::binary_search(b, b + 5, 6)
来判断数组中是否有6,在这个例子中是true。
std::lower_bound()
std::lower_bound()
:这个函数用于在一个已经排序的范围内查找第一个不小于给定值的元素,返回一个指向该元素的迭代器,如果没有找到则返回范围的结束迭代器。
- 6.1 例如,如果我们有一个整数向量
std::vector<int> v = {1, 2, 4, 6, 8};
,我们可以用std::lower_bound(v.begin(), v.end(), 5)
来查找第一个不小于5的元素,在这个例子中是6。
std::upper_bound()
std::upper_bound()
:这个函数用于在一个已经排序的范围内查找第一个大于给定值的元素,返回一个指向该元素的迭代器,如果没有找到则返回范围的结束迭代器。
- 7.1 例如,如果我们有一个整数向量
std::vector<int> v = {1, 2, 4, 6, 8};
,我们可以用std::upper_bound(v.begin(), v.end(), 5)
来查找第一个大于5的元素,在这个例子中是6。
std::equal_range()
std::equal_range()
:这个函数用于在一个已经排序的范围内查找等于给定值的一段连续元素,返回一个包含两个迭代器的pair,分别指向该段元素的起始和结束位置,如果没有找到则返回两个相等的迭代器。
- 8.1 例如,如果我们有一个整数向量
std::vector<int> v = {1, 2, 4, 4, 4, 6, 8};
,我们可以用std::equal_range(v.begin(), v.end(), 4)
来查找等于4的一段元素,在这个例子中返回的pair是{v.begin() + 2, v.begin() + 5}³。
时间复杂度
std::find()
:线性时间复杂度,即O(n)std::count()
:线性时间复杂度,即O(n)std::find_if()
:线性时间复杂度,即O(n)std::any_if()
:线性时间复杂度,即O(n)std::binary_search()
:对数时间复杂度,即O(log n)std::lower_bound()
:对数时间复杂度,即O(log n)std::upper_bound()
:对数时间复杂度,即O(log n)std::equal_range()
:对数时间复杂度,即O(log n)
执行效率由高到低排序
std::binary_search()
std::lower_bound()
std::upper_bound()
std::equal_range()
std::find()
std::count()
std::find_if()
std::any_if()