954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Linear search algorithm

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 & v, int x )
{
if find (v.begin(), v.end(), x);
return true;
else
return false;
}

Commonman4012
Newbie Poster
1 post since Feb 2012
Reputation Points: 10
Solved Threads: 0
 

std::find() doesn't return a bool , it returns aniterator (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

ravenous
Posting Pro
516 posts since Jul 2005
Reputation Points: 269
Solved Threads: 92
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You