目录
1. 动态数组
2.静态数组
避免"索引越界"错误的规则如下(针对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
1. 动态数组
采用的办法是继承std::vector
实现代码和测试如下:
//scpp_vector.h#ifndef _SCPP_VECTOR_#define _SCPP_VECTOR_
#include
namespace scpp {
//wrapper around std::vector,在[]提供了临时的安全检查:重载[] <<运算符template
//常用的构造函数 commonly use cons explicit vector(size_type n=0) : std::vector
}vector(size_type n,const T& value) : std::vector
}
template
}
//Note : we don't provide a copy-cons and assignment operator ?
//使用scpp::vector提供更安全的下标访问实现,它可以捕捉越界访问错误T& operator[] (size_type index) {SCPP_ASSERT( index < std::vector
//? difference const T& operator[] (size_type index) const {SCPP_ASSERT( index < std::vector
//允许此函数访问这个类的私有数据//friend std::ostream& operator<< (std::ostream& os,const ) ?};} //namespace
template #endif //test_vector.cpp#include "scpp_vector.h"#include using namespace std;int main() {//usage-创建一个具有指定数量的vector:scpp::vector for(int i=0;i <= vec.size();i++) {cout << "Value of vector at index " << i << " is " << vec[i] << endl;}return 0;}我们直接使用scpp::vector而尽量不与std::vector交叉使用。 静态数组是在栈上分配内存,而vector模板是在构造函数中用new操作符分配内存的,速度相对慢些,为保证运行时效率,建议使用array模板(同样也是栈内存),实现代码和测试如下: #include "scpp_assert.h" namespace scpp { //wrapper around std::vector,在[]提供了临时的安全检查//fixed-size array template //常用的构造函数 commonly use cons array() {}explicit array(const T& val) {for(unsigned int i=0;i < N;i++) {m_data[i]=val;}} size_type size() const {return N;} //must use const if we use the size() //Note : we don't provide a copy-cons and assignment operator ? T& operator[] (size_type index) {SCPP_ASSERT( index < N,"Index " << index << " must be less than " << N);return m_data[index];} //? difference const T& operator[] (size_type index) const {SCPP_ASSERT( index < N ,"Index " << index << " must be less than " << N);return m_data[index];} //模拟迭代器的begin和end方法//访问方法accessors T* begin() {return &m_data[0];} const T* begin() const {return &m_data[0];} //返回越过数组尾部的迭代器T* end() {return &m_data[N];} const T* end() const {return &m_data[N];}private:T m_data[N];};} //namespace scpp template //test_array.cpp#include "scpp_array.h"#include cout << "Array before sort : " << arr << endl;sort(arr.begin(),arr.end());cout << "Array after sort : "<< arr << endl; arr[5]=8;return 0;}到此这篇关于C++索引越界的解决方法的文章就介绍到这了,更多相关C++索引越界内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 您可能感兴趣的文章:c++ map索引不存在的key可能导致的后果分析C++二分查找在搜索引擎多文档求交的应用分析2.静态数组
//scpp_array.h#ifndef _SCPP_ARRAY_H_#define _SCPP_ARRAY_H_
