0

I have an assignment that I am working on that has the function outline provided. I am supposed to return the position of the found item if it is found or -1 if not. Here is that outline code:

int linearSearch( const vector<int>& inputVec, int x)  {

and I have to fill in the function using the find algorithm. My understanding is that find returns an iterator. I'm just not sure how to take that and return an integer that is the position or a -1. Right now I am trying this on the inside.

auto it = find(inputVec.begin(), inputVec.end(), x);

and I'm not sure where to go from there.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    I doubt you're supposed to it this way. A direct linear search would be a lot faster most likely. Either way, if you absolutely want to it using `std::find`, this is a duplicate of [this question](http://stackoverflow.com/questions/2152986/what-is-the-most-effective-way-to-get-the-index-of-an-iterator-of-an-stdvector). –  Feb 12 '17 at 04:03
  • 1
    You can check the range between the `it` and `inputVec.begin()`. – Fureeish Feb 12 '17 at 04:03

1 Answers1

2

You can do manual looping like this:

for(int i=0;i<inputVec.size();i++) {
    if(inputVec[i]==x) return i;
}
return -1;

Or if you want to use find() function:

auto it = find(inputVec.begin(), inputVec.end(), x);
if(it==inputVec.end()) return -1;
return it - inputVec.begin();
algojava
  • 743
  • 4
  • 9
  • That doesn't seem to be using the `find` algorithm as required by the assignment. – Jonathan Leffler Feb 12 '17 at 05:40
  • if(it==inputVec.end()) return -1; else return it - inputVec.begin(); – algojava Feb 12 '17 at 05:41
  • That looks better...now check it and then add it to your answer. – Jonathan Leffler Feb 12 '17 at 05:44
  • the assignment ask to implement linearSearch(), I am not sure why he wrap the find() function. – algojava Feb 12 '17 at 05:46
  • The assignment is: _Here is that outline code: `int linearSearch( const vector& inputVec, int x) {` and I have to fill in the function using the `find` algorithm._ So, the function he has to write is called `linearSearch()` and he is supposed to use `find` inside the function. It doesn't seem to be particularly difficult to understand. – Jonathan Leffler Feb 12 '17 at 05:48
  • I used the second version to incorporate the find function. But it doesn't seem to like the if statement that comes after it. I get the error message: no match for 'operator==' (operand types are 'std::pair<__gnu_cxx >, __gnu_cxx::__normal_iterator > >' and 'std::vector::const_iterator {aka __gnu_cxx::__normal_iterator >}' ) – Cameron Douthitt Feb 13 '17 at 22:12