0

During the execution of the program the above error is displayed.

Aim of the code is to print "Yes" if the number 'h' is present in v vector and its corresponding index . If the number is not present you have to print "No" followed by the index of the next smallest number just greater than that number.

Thank you for help in advance.

    cin >> h; //value to be searched in vector v
    vector<int>::iterator lower;
    lower=lower_bound(v.begin(),v.end(),h);
    if(*(lower) == h){
        cout<<"Yes "<<lower<<endl;
    }else{
        cout<<"No "<<lower<<endl;
yash
  • 77
  • 3
  • 10
  • In the comparison you're dereferencing the iterator `lower`. You need to do that when printing as well. – Some programmer dude May 18 '20 at 07:09
  • 1
    You also need to check in the `else` case that the iterator can be dereferenced, if all the items in the vector are less than `h` then `*lower` would be an error. – john May 18 '20 at 07:10
  • @john if item not found till the end of the list then lower will automatically point the very last integer of vector. I don't think it would be a problem – yash May 18 '20 at 07:14
  • [`std::lower_bound`](https://en.cppreference.com/w/cpp/algorithm/lower_bound) returns the "last" iterator, which in your case is `v.end()`, which can't be dereferenced. And you need to check for this before attempting to dereference the iterator in the condition as well. – Some programmer dude May 18 '20 at 07:19
  • @Some programmer dude It would be appreciated if you help me in understand that why we cannot dereference v.end(). – yash May 18 '20 at 07:24
  • Because the "end" iterator is one *beyond* the last element of the container. That makes iterators work like zero-base indexing. You know that an array of `N` elements have indexes from `0` to `N - 1`? It's the same thing here, the "end" is outside the range of valid elements. Any decent book, tutorial or class should have contained that information. – Some programmer dude May 18 '20 at 07:29
  • @YashpriyadeepKatta [Recommended book list](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – john May 18 '20 at 08:07

0 Answers0