Блог пользователя vedant-z

Автор vedant-z, история, 19 месяцев назад, По-английски

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’)

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
19 месяцев назад, # |
  Проголосовать: нравится +5 Проголосовать: не нравится

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.

»
19 месяцев назад, # |
  Проголосовать: нравится +5 Проголосовать: не нравится

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().

»
19 месяцев назад, # |
Rev. 2   Проголосовать: нравится +1 Проголосовать: не нравится
auto iterator = upper_bound(v.begin(), v.end(), M);
if(iterator == v.end()){
     do_something();
}
int index = iterator - v.begin();
»
19 месяцев назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

define i as long long or int

  • »
    »
    19 месяцев назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

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

  • »
    »
    19 месяцев назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится
    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.