c++ find函数返回值
时间: 2023-06-24 21:06:14 浏览: 70
C++中的`find()`函数用于在容器中查找指定元素,如果找到了该元素,则返回该元素在容器中的迭代器。如果未找到该元素,则返回容器的`end()`迭代器。例如:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v{1, 2, 3, 4, 5};
auto it = std::find(v.begin(), v.end(), 3);
if (it != v.end()) {
std::cout << "Found at position " << std::distance(v.begin(), it) << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
```
输出结果为:
```
Found at position 2
```
相关问题
c++ string find函数返回值
C++ 中的 `string` 类型的 `find()` 函数可以用于查找一个子串在另一个字符串中出现的位置。它的返回值是 `string::size_type` 类型,表示子串在字符串中第一次出现的位置(从 0 开始计数),如果没有找到,则返回 `string::npos`。`string::npos` 是一个常量,它的值通常是 `-1`(或者是 `std::string::size_type(-1)`)。因此,可以根据 `find()` 函数的返回值来判断是否找到了子串。例如:
```c++
#include <iostream>
#include <string>
int main() {
std::string str = "hello world!";
std::string sub = "world";
std::string::size_type pos = str.find(sub);
if (pos != std::string::npos) {
std::cout << "Found at position " << pos << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
```
输出结果为:
```
Found at position 6
```
string的find函数返回值
`std::string`的`find`函数用于在字符串中查找指定的子串,并返回匹配子串的第一个字符的位置。如果找到了匹配子串,则返回该子串在字符串中的起始位置;如果没有找到,返回`std::string::npos`,即一个静态常量,表示未找到。
具体来说,`std::string::find`函数的声明如下:
```C++
size_t find(const std::string& str, size_t pos = 0) const noexcept;
```
其中,`str`是要查找的子串,`pos`是查找的起始位置,默认为0,表示从字符串的开头查找。函数返回值的类型是`size_t`,即无符号整数类型,表示匹配子串在字符串中的起始位置。
如果找到了匹配子串,则返回匹配子串在字符串中的起始位置,该位置从0开始计数;如果没有找到,则返回`std::string::npos`,该常量的值通常为一个大整数,例如4294967295,在一些编译器中也可以写作-1。因此,我们可以通过判断`find`函数的返回值是否等于`std::string::npos`,来确定是否找到了匹配子串。