find函数在< algorithm >库中,使用时注意导入,
find函数的定义如下所示:
_InputIterator find(_InputIterator __first, _InputIterator __last, const _Tp& __val)
数组中:
参数中,第一个为数组的起始位置,第二个为数组的终点,可以这样理解[begin, end),在这个范围内查找val这个值,注意它的返回类型是一个迭代器,与指针类似,这意味着我们不能直接把它作为下标来使用,但是用它减去_InputIterator __first就是我们需要的下标了
#include <iostream>
#include <algorithm>
using namespace std;
int main(void){
int a[5] = {5,3,2,1,4};
int* q = find(a, a+5, 3);
int r = q - a;
printf("位置为:%d\n", r);
printf("值为:%d\n", *q);
return 0;
}
```
string:
返回值是目标元素的下标,找不到时返回值为迭代器结尾
力扣28:
```cpp
//查找第一次出现的目标字符串:说明:如果查找成功则输出查找到的第一个位置,否则返回-1;
class Solution {
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.empty())
return 0;
int pos=haystack.find(needle);
return pos;
}
};
查找从指定位置开始的第一次出现的目标字符串:
#include <iostream>
#include <csdtio>
using namespace std;
int main() {
string s1 = "abcdef";
string s2 = "de";
int ans = s1.find(s2, 2) ; //从S1的第二个字符开始查找子串S2
cout << ans << endl;
system("pause");
}
此外还有find_first_of()和 find_last_of(),匹配第一个或最后一个查找到的位置,未找到返回-1.