且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

引用绑定到类型为'value_type'的空指针

更新时间:2021-10-23 01:54:28

vector< T> :: size()返回类型为 size_t 的值无符号类型.假设传入的向量为空,因此向量的长度为0. nums.size()-1 将导致整数下溢,您实际上将把 0 与一个非常大的正数.这将评估为true,从而导致循环运行,并且 i 越过数组范围.

vector<T>::size() returns a value of type size_t, which is an unsigned type. Let's say the vector passed in is empty and therefore the vector's length is 0. nums.size() - 1 will cause integer underflow and you will actually be comparing 0 with a very large positive number. This will evaluate to true causing the loop to run and i going pass the array bounds.

要解决此问题,您可以抢先将 nums.size()强制转换为 int 或将大小存储在整数变量中并与之进行比较.

To fix this you can cast nums.size() to int preemptively or store the size in an integer variable and compare with that.