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;
else
return false;
}

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.