I'm trying to make a Boolean function that will search the elements of a vector of strings and return true if the user-inputted string is present. For instance, if the vector contains the strings "red," "yellow," and "blue" and the user inputs the value "green," the function returns false.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
bool appears_in_vector(vector<string>vec, string input)
{
for (int i = 0; i < vec.size(); i++)
{
if (input == vec[i])
{
returntrue;
}
else
{
returnfalse;
}
}
}
This function gives me run-time errors. What is the correct way to do this?
I don't see anything that would cause run time errors, but your logic is flawed and will not give you the results you want.
Your logic is guaranteed to exit on the first comparison and will not check all the members of the vector.
Try this instead:
1 2 3 4 5 6 7
bool appears_in_vector(vector<string>vec, string input)
{ for (int i = 0; i < vec.size(); i++)
{ if (input == vec[i])
returntrue;
}
returnfalse; // no matches found
}