how to compare value of variable with value of all elements in vector?

178 views Asked by At
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?

1

There are 1 answers

1
Remy Lebeau On

In the statement if (y == in), in is the last input value that was pushed into the vector. So, you are simply comparing if the value of y is equal to the previous input value that preceded it, without any regard to the contents of the vector at all.

If your goal is to check whether the value of y exists in the vector, you should be using std::find() instead of std::lower_bound() (and, you won't need the std::sort() anymore, either), eg:

vector<int>::iterator iter;
iter = find(v.begin(), v.end(), y);
if (iter != v.end()) {
    cout << "Yes" << " " << distance(v.begin(), iter) + 1 << "\n";
}
else {
    cout << "No" << "\n";
}