Boolean Function to search Vector Elements??

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])
		{
			return true;
		}
		else
		{
			return false;
		}
	}
		
}


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])
           return true;
     }
    return false; // no matches found		
}

Last edited on
Thanks!
Topic archived. No new replies allowed.