Hi I'm having a lot of trouble with this problem. Here is the assignment...

Write the definition of the function template seqSearch to implement the sequential search on a vector object.

template<class elemType>
int seqSearch(const vector<elemType> &list, const elemType& item);
     //If item is found in the list, return the
     //position of the item in the list; otherwise, returns -1.

Also, write a program to test the function seqSearch. Use the function push_back to insert elements in the vector object.

I can write a test function easily, i just cant even get a start on the actual function, I've tried multiple times and each time I've got a cluster f*&k of errors, so any help writing a function following that prototype would be much appreciated.

Recommended Answers

All 2 Replies

First think of what you need that you don't already have. In this case you need an int to return when the function is over, and it should probably have something to do with what the function is supposed to do, like index or position.

Then you can use the int called index to indicate the location of the current element within the array that you are evaluating for equality to the target called item. (Be careful how you check for equality with numerical types such as double or float!) If the element at position index is equal to the target then you can stop the search and return the current value of index. You can do a brute force search starting with element of index equal to zero up to, but not including size(); or you can use an iterator ranging from begin() to end() keeping track of which index you're at as you go by incrementing index if no equality found. If you get out of the loop without returning then you can assign the value of -1 to index and return that. If you don't like two return statements within the function then you can stop the searching when equality is found and if index equals size() or iterator equals end()at the end of searching then assign -1 to index before returning it.

I haven't written a test program yet but here is my code...

     int location;
     bool found = false;

     for(location=0; location<list.size(); location)
          if(list.at(location) == item)
               found = true;

Does this look like it will work well do you see any mistakes?

Be a part of the DaniWeb community

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