C++索引越界的解決方法
避免"索引越界"錯誤的規(guī)則如下(針對C++):
- 不要使用靜態(tài)或動態(tài)分配的數(shù)組,改用array或vector模板
- 不要使用帶方括號的new和delete操作符,讓vector模板為多個元素分配內(nèi)存
- 使用scpp::vector代替std::vector,使用scpp::array代替靜態(tài)數(shù)組,并打開安全檢查(自動在使用下標訪問提供了索引邊界檢查)
C++中創(chuàng)建類型T的對象的數(shù)組方式如下:
#define N 10 T static_arr[N]; //數(shù)組長度在編譯時已知 int n=20; T* dynamic_arr=new T[n]; //數(shù)組長度在運行時計算 std::vector<T> vector_arr; //數(shù)組長度在運行時進行修改
1. 動態(tài)數(shù)組
采用的辦法是繼承std::vector<T>,并重載<< 、[]運算符,提供一個能夠捕捉越界訪問錯誤的實現(xiàn)。
實現(xiàn)代碼和測試如下:
//scpp_vector.h
#ifndef _SCPP_VECTOR_
#define _SCPP_VECTOR_
#include <vector>
#include "scpp_assert.h"
namespace scpp {
//wrapper around std::vector,在[]提供了臨時的安全檢查:重載[] <<運算符
template<typename T>
class vector : public std::vector<T> {
public:
typedef unsigned size_type;
//常用的構(gòu)造函數(shù) commonly use cons
explicit vector(size_type n=0) : std::vector<T>(n) {
}
vector(size_type n,const T& value) : std::vector<T>(n,value) {
}
template <class InputIterator> vector(InputIterator first,InputIterator last)
: std::vector<T>(first,last) {
}
//Note : we don't provide a copy-cons and assignment operator ?
//使用scpp::vector提供更安全的下標訪問實現(xiàn),它可以捕捉越界訪問錯誤
T& operator[] (size_type index) {
SCPP_ASSERT( index < std::vector<T>::size() ,
"Index " << index << " must be less than " << std::vector<T>::size());
return std::vector<T>::operator[](index);
}
//? difference
const T& operator[] (size_type index) const {
SCPP_ASSERT( index < std::vector<T>::size() ,
"Index " << index << " must be less than " << std::vector<T>::size());
return std::vector<T>::operator[](index);
}
//允許此函數(shù)訪問這個類的私有數(shù)據(jù)
//friend std::ostream& operator<< (std::ostream& os,const ) ?
};
} //namespace
template<typename T>
inline std::ostream& operator<< (std::ostream& os,const scpp::vector<T>& v) {
for(unsigned i=0 ;i<v.size();i++) {
os << v[i];
if( i+1 < v.size()) os << " ";
}
return os;
}
#endif
//test_vector.cpp
#include "scpp_vector.h"
#include <iostream>
using namespace std;
int main() {
//usage-創(chuàng)建一個具有指定數(shù)量的vector:scpp::vector<int> v(n); 把n個vector元素都初始化為一個值:scpp::vector<int> v(n,val)
//方法3:scpp::vector<int> v; v.reserve(n),表示開始的vector是空的,對應的size()為0,
//并且開始添加元素時,在長度達到n之前,不會出現(xiàn)導致速度降低的容量增長現(xiàn)象
scpp::vector<int> vec;
for(int i=0;i< 3;i++){
vec.push_back(4*i);
}
cout << "The vector is : "<< vec <<endl;
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交叉使用。
2.靜態(tài)數(shù)組
靜態(tài)數(shù)組是在棧上分配內(nèi)存,而vector模板是在構(gòu)造函數(shù)中用new操作符分配內(nèi)存的,速度相對慢些,為保證運行時效率,建議使用array模板(同樣也是棧內(nèi)存),實現(xiàn)代碼和測試如下:
//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<typename T,unsigned int N>
class array {
public:
typedef unsigned int size_type;
//常用的構(gòu)造函數(shù) 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];
}
//返回越過數(shù)組尾部的迭代器
T* end() {
return &m_data[N];
}
const T* end() const {
return &m_data[N];
}
private:
T m_data[N];
};
} //namespace scpp
template<typename T,unsigned int N>
inline std::ostream& operator<< (std::ostream& os,const scpp::array<T,N>& v) {
for(unsigned int i=0 ;i< N;i++) {
os << v[i];
if( i+1 < v.size()) os << " ";
}
return os;
}
#endif
//test_array.cpp
#include "scpp_array.h"
#include <iostream>
#include <algorithm> //sort algorithm
using namespace std;
int main() {
//use vector/array class instead of static array or dynamic array
scpp::array<int,5u > 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++索引越界的解決方法的文章就介紹到這了,更多相關C++索引越界內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C++ 中dynamic_cast<>的使用方法小結(jié)
將一個基類對象指針(或引用)cast到繼承類指針,dynamic_cast會根據(jù)基類指針是否真正指向繼承類指針來做相應處理2013-03-03

