给我列举C++详细的find使用例子
时间: 2024-02-16 15:00:47 浏览: 35
C++中的`find()`函数可以用于在字符串或容器中查找指定元素的位置,下面是一些`find()`使用的例子:
1. 在字符串中查找单个字符
```c++
string str = "Hello, World!";
char ch = 'W';
size_t found = str.find(ch);
if (found != string::npos) {
cout << "Found " << ch << " at position " << found << endl;
}
else {
cout << "Not found" << endl;
}
// Output: Found W at position 7
```
2. 在字符串中查找子串
```c++
string str = "Hello, World!";
string subStr = "World";
size_t found = str.find(subStr);
if (found != string::npos) {
cout << "Found " << subStr << " at position " << found << endl;
}
else {
cout << "Not found" << endl;
}
// Output: Found World at position 7
```
3. 在容器中查找元素
```c++
vector<int> vec = {1, 2, 3, 4, 5};
int num = 3;
auto it = find(vec.begin(), vec.end(), num);
if (it != vec.end()) {
cout << "Found " << num << " at position " << it - vec.begin() << endl;
}
else {
cout << "Not found" << endl;
}
// Output: Found 3 at position 2
```
4. 在容器中查找符合条件的元素
```c++
vector<int> vec = {1, 2, 3, 4, 5};
auto it = find_if(vec.begin(), vec.end(), [](int x){ return x > 3; });
if (it != vec.end()) {
cout << "Found " << *it << " at position " << it - vec.begin() << endl;
}
else {
cout << "Not found" << endl;
}
// Output: Found 4 at position 3
```