Hello World!

I am having trouble with a linear search algorithm function that I have to write for a program. The direction for this function states:

A linear search algorithm, where x is the searched item in vector v. It simply starts searching for x from the beginning of the vector v to the end, but it stops searching when there is a match. If the search is successful, it returns true; otherwise, it returns false. To implement this routine, simply call the find ( ) function in the STL.

Below is what I have and it keeps printing out zeros instead of integers. Any ideas how to make it works? Thanks.

bool linearSearch ( const vector <int>& v, int x )
if find (v.begin(), v.end(), x);
return true;
return false;

5 Years
Discussion Span
Last Post by ravenous

std::find() doesn't return a bool , it returns an iterator (kind of like a pointer) to the element that you're looking for in the find. If it doesn't find the thing that you're looking for, the iterator points to the element one-past-the-end of the container. So, you need something more like: if ( std::find( v.begin(), v.end(), x ) != v.end() ) You can read more about std::find and other STL algorithms here

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.