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

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

I recently faced an issue due the fact that I didn't placed an 'int' before the looping for a vector that was constructed. It works without (int) sometimes but this time It gave warnings. Can someone explain this behavior. Thankyou.

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

»
20 месяцев назад, # |
Rev. 2   Проголосовать: нравится +43 Проголосовать: не нравится

The function size()'s return type is size_t which is an unsigned int.
So, for example, if you do v.size() - 1 for an empty vector(size = 0) it will not result in -1 but some large number.
Maybe you did something similar to this.

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

This doesn't answer your question, but it's pretty common to define a macro #define sz(c) int((c).size()) to avoid underflow issues without having to put int() all over the place. Alternatively, in C++20 you can use ssize(c) (see cppreference), which returns the size in a signed type.