I would like to know how i can write an if and else statement for a vector. So let's say i have a vector which includes 1,2,3,4,5. I want the if statement to return a string if the number 1 is inside the vector. I know how to structure it but how do i write the statement. I have writen an example below with question marks because I'm unsure what is supposed to be in the brackets.
vector <int> myvec {1,2,3,4,5};
if (myvec??? 1) [
cout << "yes it is there" << endl;
]
You might use std::find
:
std::vector<int> myvec {1,2,3,4,5};
if (std::find(myvec.begin(), myvec.end(), 1) != myvec.end()) {
std::cout << "yes it is there" << std::endl;
}
In C++23, there is even std::ranges::contains
:
if (std::ranges::contains(myvec, 1)) {
std::cout << "yes it is there" << std::endl;
}