I’m having trouble comparing size of vector and simple constant -1
I think both
(index >= (arr.size() - 1))((index + 1) >= arr.size())
are logically same.
However, the first one returns 1 not 0.
What’s the difference between two comparation?
#include <iostream>
#include <vector>
using namespace std;
int main() {
int index = -1;
vector<char> arr(6);
cout << (index >= (arr.size() - 1)) << endl;
cout << ((index + 1) >= arr.size()) << endl;
}
>Solution :
The arr.size method returns an unsigned integer type, so the type of the right-hand side of the comparison is unsigned. This results in the left side being converted to unsigned.
When the value on the left is -1, this gets converted to a very large unsigned number, resulting in the first comparison being true. In the second case, the value on the left is 0 so it doesn’t change when being converted to an unsigned type and the comparison is false.