Search code examples
c++vectorfind

How to search in a given interval of a vector container


I want to search in a given interval (not a whole vector) of a vector container to see whether a user-specified integer is present or not. But I couldn't make it work. Thank you very much.

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main () 
{
int myints[] = { 10, 20, 30 ,40 };
vector<int> myvector (myints,myints+4);
vector<int>::iterator it, itLower, itUpper;
itLower = myvector.begin();
itUpper = myvector.begin();
advance(itLower, 1);
advance(itUpper, 2);

// iterator to vector element:
it = find (itLower, itUpper, 50);

if (it != myvector.end())
{  
   // Found
   cout << "Found it";
}
else
{ 
   // Not fount
   cout << "Not found it";
}

return 0;
}

Solution

  • You may just replace the line

    if (it != myvector.end()) ...
    

    by

    if (it != itUpper) ...
    

    If find does not find the item it returns the last element (which is in your case the end of your range and not of the complete vector). Note that the range is defined with itUpper exclusive.