目录
1.find()
find函数在使用的时候需要三个参数:起始位置First和终止位置Last(非必需),需要搜索的值Value(必需)
例子如下:👇
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {4, 2, 7, 5, 9, 1, 8};
int target = 5;
auto it = std::find(vec.begin(), vec.end(), target);//分别确定起始位置,终止位置(即遍历vector)
if (it != vec.end()) {
std::cout << "找到目标元素 " << target << " 在向量中的位置: " << std::distance(vec.begin(), it) << std::endl;
} else {
std::cout << "未找到目标元素 " << target << std::endl;
}
return 0;
}
该函数返回指向第一次出现指定元素的迭代器 ,若没有搜索到想要的值,则返回Last.
2.count()
同find()函数一样,count()函数接收三个参数:起始位置First,终止位置Last,搜索的特定值Value
例子如下:👇
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> myVector = {1, 2, 3, 4, 1, 2, 1, 5, 2};
// 统计向量中元素2的出现次数
int countOf2 = std::count(myVector.begin(), myVector.end(), 2);
std::cout << countOf2 << std::endl;
return 0;
}
该函数返回特定值Value重复出现的次数,若没有查找到Value,则返回0
3.adjacent_find()
该函数接收两个参数:起始位置First和终止位置Last
使用该函数,将会在给定的范围(First和Last之间)查找相邻的元素,如果查找到相邻的重复元素,则返回指向第一个重复元素的迭代器,否则返回Last
4.find_if()
该函数接收三个参数:起始位置First,终止位置Last,一个可调用对象P(用于检查元素是否符合特定条件)
例子如下:👇
#include <iostream>
#include <vector>
#include <algorithm>
bool isGreaterThanThree(int num) {
return num > 3;
}
int main() {
std::vector<int> myVector = {1, 2, 3, 4, 5, 6};
// 查找大于3的第一个元素
auto it = std::find_if(myVector.begin(), myVector.end(), isGreaterThanThree);
if (it != myVector.end()) {
std::cout << "First element greater than 3: " << *it << std::endl;
} else {
std::cout << "No element greater than 3 found in the vector." << std::endl;
}
return 0;
}
在这个例子中,程序设计了一个寻找小于3的函数,并通过find_if()函数实现
如果找到符合条件的元素,则返回指向该元素的迭代器,否则返回Last
5.count_if()
该函数的使用方法与find_if()几乎完全相同,不同的是count_if()函数返回的是满足条件的元素的个数,例子如下:👇
#include <iostream>
#include <vector>
#include <algorithm>
bool isGreaterThanThree(int num) {
return num > 3;
}
int main() {
std::vector<int> myVector = {1, 2, 3, 4, 5, 6};// 统计大于3的元素个数
int count = std::count_if(myVector.begin(), myVector.end(), isGreaterThanThree);
std::cout << "Number of elements greater than 3: " << count << std::endl;
return 0;
}
6.binary_search()
函数接收:起始位置First,终止位置Last,需要查找的值Value
该函数常用于二分查找,可以提高查找的效率,使算法更加高效,该算法的时间复杂度为O(log n)
例子如下:👇
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 3, 5, 7, 9, 11, 13, 15, 17};
int target = 7;
bool found = std::binary_search(vec.begin(), vec.end(), target);
if (found) {
std::cout << "目标元素 " << target << " 存在于向量中" << std::endl;
} else {
std::cout << "目标元素 " << target << " 不存在于向量中" << std::endl;
}
return 0;
}
如果存在Value,则函数返回true,否则返回false.
--------------------------------------------------------------------------------------------------------------------------------
觉得有用就点点关注收藏一下吧~谢谢!