I'm trying to compare the element pointed by an iterator to an integer, but so far i haven't had any luck in doing so. please correct whatever i'm doing wrong. Thank you.

vector<int>::iterator y;

for (int i = 0;i<n2;i++)
        {
            cin>>temp;
            cnt = 0;
            y = lower_bound(a.begin(),a.end(),temp);
             if (*y == temp) cout <<temp<<"found at"<<int(y-a.begin()+1)<<endl; 
             else cout<<temp<<"Not found"<<endl;
        }

error msg = "vector iterator not dereferencable"

This code compiles with vc++ 2012 RC, but its not tested.

void foo(int n2, vector<int> a)
{
    int temp, cnt;
    vector<int>::iterator y;
    for (int i = 0;i<n2;i++)
    {
            cin>>temp;
            cnt = 0;
            y = lower_bound(a.begin(),a.end(),temp);
             if (*y == temp) cout <<temp<<"found at"<<int(y-a.begin()+1)<<endl; 
             else cout<<temp<<"Not found"<<endl;
    }
}

Instead of if (*y == temp) to test if the element was found, you need to use this test:

if( y != a.end() )

Because if the element is not found, "y" will be equal to the end iterator, which means that it will be "not dereferencable".

@mike200017 Actually if the element is not found there is no guarantee that "y" will point to the end iterator. Given an array of 2,3,5,7,9 lower_bound(..,6) will point to 7. Your code works(I no longer get the error) but it doesn't return the correct value :(

Nvm I fixed it

for (int i = 0;i<n2;i++)
        {
            cin>>temp;
            y = lower_bound(a.begin(),a.end(),temp);
            if (y == a.end()) cout<<temp<<" not found"<<endl;
            else
            {
            if (*y == temp) cout <<temp<<" found at "<<int(y-a.begin()+1)<<endl;
            else cout<<temp<<" not found"<<endl;
            }
        }
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.