C++索引越界的解决方法

本文主要介绍了C++索引越界的解决方法,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

避免"索引越界"错误的规则如下(针对C++):

  • 不要使用静态或动态分配的数组,改用array或vector模板
  • 不要使用带方括号的new和delete操作符,让vector模板为多个元素分配内存
  • 使用scpp::vector代替std::vector,使用scpp::array代替静态数组,并打开安全检查(自动在使用下标访问提供了索引边界检查)

C++中创建类型T的对象的数组方式如下:

 #define N 10 T static_arr[N]; //数组长度在编译时已知 int n=20; T* dynamic_arr=new T[n]; //数组长度在运行时计算 std::vector vector_arr; //数组长度在运行时进行修改 

1. 动态数组

  采用的办法是继承std::vector,并重载<< 、[]运算符,提供一个能够捕捉越界访问错误的实现。

  实现代码和测试如下:

 //scpp_vector.h #ifndef  _SCPP_VECTOR_ #define  _SCPP_VECTOR_ #include  #include "scpp_assert.h" namespace scpp { //wrapper around std::vector,在[]提供了临时的安全检查:重载[] <<运算符 template class vector : public std::vector { public: typedef unsigned size_type; //常用的构造函数 commonly use cons explicit vector(size_type n=0) : std::vector(n) { } vector(size_type n,const T& value) : std::vector(n,value) { } template  vector(InputIterator first,InputIterator last) : std::vector(first,last) { } //Note : we don't provide a copy-cons and assignment operator  ? //使用scpp::vector提供更安全的下标访问实现,它可以捕捉越界访问错误 T& operator[] (size_type index) { SCPP_ASSERT( index ::size() , "Index " << index << " must be less than " << std::vector::size()); return std::vector::operator[](index); } //? difference const T& operator[] (size_type index) const { SCPP_ASSERT( index ::size() , "Index " << index << " must be less than " << std::vector::size()); return std::vector::operator[](index); } //允许此函数访问这个类的私有数据 //friend std::ostream& operator<< (std::ostream& os,const ) ? }; } //namespace template inline  std::ostream& operator<< (std::ostream& os,const scpp::vector& v) { for(unsigned i=0 ;i using namespace std; int main() { //usage-创建一个具有指定数量的vector:scpp::vector v(n); 把n个vector元素都初始化为一个值:scpp::vector v(n,val) //方法3:scpp::vector v; v.reserve(n),表示开始的vector是空的,对应的size()为0, //并且开始添加元素时,在长度达到n之前,不会出现导致速度降低的容量增长现象 scpp::vector vec; for(int i=0;i<3;i++){ vec.push_back(4*i); } cout << "The vector is : "<< vec <

  我们直接使用scpp::vector而尽量不与std::vector交叉使用。

2.静态数组

  静态数组是在栈上分配内存,而vector模板是在构造函数中用new操作符分配内存的,速度相对慢些,为保证运行时效率,建议使用array模板(同样也是栈内存),实现代码和测试如下:

 //scpp_array.h #ifndef _SCPP_ARRAY_H_ #define _SCPP_ARRAY_H_ #include "scpp_assert.h" namespace scpp { //wrapper around std::vector,在[]提供了临时的安全检查 //fixed-size array template class array { public: typedef unsigned int size_type; //常用的构造函数 commonly use cons array() {} explicit array(const T& val) { for(unsigned int i=0;i  inline  std::ostream& operator<< (std::ostream& os,const scpp::array& v) { for(unsigned int i=0 ;i #include  //sort algorithm using namespace std; int main() { //use vector/array class instead of static array or dynamic array scpp::array arr(0); arr[0]=7; arr[1]=2; arr[2]=3; arr[3]=9; arr[4]=0; cout << "Array before sort : " << arr << endl; sort(arr.begin(),arr.end()); cout << "Array after sort : "<< arr << endl; arr[5]=8; return 0; } 

以上就是C++索引越界的解决方法的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » C语言