使用vector的误区.size()

 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
...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值