How to check if an element exists in std::vector? (C++)
Hello everyone! I just started learning C++ and ran into a problem. I have a std::vector numbers = {10, 20, 30, 40, 50}. I need to write a function that checks if the number 30 is in this vector. I know that in Python you can simply use the in operator: if 30 in numbers: print("Found!"). But in C++ it doesn't work that way.
I tried writing a loop manually, but my code looks terrible and I'm not sure it's the right approach. Here's what I did:
```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 (f
No answers yet.
Log in to leave an answer