vector<int> v;
int n, in;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> in;
v.push_back(in);
}
sort(v.begin(), v.end());
int y;
cin >> y;
vector<int>::iterator low;
low = lower_bound(v.begin(), v.end(), y);
if (y == in) {
cout << "Yes" << " " << (low - v.begin() + 1) << "\n";
}
else {
cout << "No" << " " << (low - v.begin() + 1) << "\n";
}
If I enter y=16, but none of the elements in vector have a value of 16, it should output the statement inside else. But it outputs the statement inside if instead.
Does anyone know how to fix my problem?
In the statement
if (y == in),inis the last input value that was pushed into thevector. So, you are simply comparing if the value ofyis equal to the previous input value that preceded it, without any regard to the contents of thevectorat all.If your goal is to check whether the value of
yexists in thevector, you should be usingstd::find()instead ofstd::lower_bound()(and, you won't need thestd::sort()anymore, either), eg: