Vector数组越界问题
在写 for 循环时候,当条件为 i < = v.size()-1的时候, 很容易出现数组越界。当v的size是0的时候,从数学上,v.size()-1 = -1,要知道v.size()是个无符号整数,根据C++的规则表达式v.size()-1 也是个无符号整数,这样-1转成无符号数的值是4294967295。
添加越界检测
// if out of bounds, writes a message (could throw an exception)
Object & operator[]( int index )
{
if (index >=0 && index <size() )
return objects[ index ];
else
cout<<"index out of bounds\n";
return objects[0];
}
const Object & operator[]( int index ) const
{
if (index >=0 && index <size() )
return objects[ index ];
else
cout<<"index out of bounds\n";
return objects[0];
}