如何检查 std::vector 中是否存在某个元素?(C++)
大家好!我刚开始学习 C++,遇到了一个问题。我有一个 std::vector numbers = {10, 20, 30, 40, 50}。我需要编写一个函数来检查这个 vector 中是否有数字 30。我知道在 Python 中可以直接使用 in 运算符:if 30 in numbers: print("找到了!")。但在 C++ 中不能这样用。
我尝试手动编写了一个循环,但我的代码看起来很糟糕,而且我不确定这是否是正确的做法。以下是我写的:
```cpp
#include
#include
int main() {
std::vector numbers = {10, 20, 30, 40, 50};
int target = 30;
bool found = false;
for (size_t i = 0; i < numbers.size(); ++i) {
if (numbers[i] == target) {
found = true;
break;
}
}
if (found) {
std::cout << "元素找到了!" << std::endl;
} else {
std::cout << "元素未找到。" << std::endl;
}
return 0;
}
```
这段代码能运行,但我觉得