vedant-z's blog

By vedant-z, history, 2 years ago, In English

If all the values in vector are less than or equal to M then "i" will point to v.end().

auto i = upper_bound(v.begin(), v.end(), M)- v.begin();

Now if I want to do certain action if "i" points to the end of vector, I tried

if(i == v.end()){ // Code }

But it doesn't work, throwing error: no match for ‘operator==’ (operand types are ‘long int’ and ‘std::vector::iterator’)

  • Vote: I like it
  • 0
  • Vote: I do not like it

»
2 years ago, # |
  Vote: I like it +5 Vote: I do not like it

You should just write auto i = upper_bound(v.begin(), v.end(), M). If you subtract v.begin() from it what you'll get will be the index corresponding to the iterator you wanted.

»
2 years ago, # |
  Vote: I like it +5 Vote: I do not like it

Use auto i = upper_bound(v.begin(), v.end(), M); is a way mentioned above. In the statement i is a vector<int>::iterator.

And you can use if(i == v.size()){ // Code } too. Here v.size() is equal to v.end() - v.begin().

»
2 years ago, # |
Rev. 2   Vote: I like it +1 Vote: I do not like it
auto iterator = upper_bound(v.begin(), v.end(), M);
if(iterator == v.end()){
     do_something();
}
int index = iterator - v.begin();
»
2 years ago, # |
  Vote: I like it 0 Vote: I do not like it

define i as long long or int

  • »
    »
    2 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    if its pointing at end that means its the largest element of vector or what data structure you are using

  • »
    »
    2 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it
    int index = upper_bound(v.begin(), v.end(), M) - v.begin();
    if(index == v.size()){
        do_something();
    }
    

    Yeah, you can use another way but it doesn't matter int or auto is here.