std::vector<PointT> points={p0,p1,p2,,,pn};
for(int i=0;i<points.size()-1;++i){
float d0 =getPointsDistance(points[i],points[i+1]);
}
上面代码是为了计算一个点集相邻两点的距离。这段代码在数组points不为空时能正常工作,然而当数组为空时,代码将会崩溃。我长期以为程序会因为i=0,points.size()-1=-1,i<points.size()-1为false,而终止下去;然而事实出乎我的意料,记录一下自己踩坑。
因为size()函数返回的是无符号整数,当数组为空(即points.size()=0)这时候再减1将会溢出。如下:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> arr;
cout<<arr.size()-1<<endl;
return 0;
}
>> 18446744073709551615
因此,如果在使用size()-1时,没有通过索引访问数组,程序将循环很多次;反之,程序会因为访问了范围外的值而崩溃;如下:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> arr;
for(int i=0;i<arr.size()-1;++i){
cout<<arr[i]<<endl;
}
return 0;
}
>> run: line 1:3 Segmentation fault (core dumped) LD_LIBRARY_PATH=/usr/local/gcc-
>> 9.2.0/lib64 ./a.out
>> Exited with error status 139
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> arr;
for(int i=0;i<arr.size()-1;++i){
cout<<i<<endl;
}
return 0;
}
>> 0
>> 1
>> 2
...