c++ vector size. why -1 is greater than zero

Because the size of a vector is an unsigned integral type. You are comparing an unsigned type with a signed one, and the two’s complement negative signed integer is being promoted to unsigned. That corresponds to a large unsigned value.

This code sample shows the same behaviour that you are seeing:

#include <iostream>
int main()
{
  std::cout << std::boolalpha;
  unsigned int a = 0;
  int b = -1;
  std::cout << (b < a) << "\n"; 
}

output:

false

Leave a Comment