溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C++中索引越界的解決方法

發(fā)布時間:2021-08-03 20:54:15 來源:億速云 閱讀:147 作者:chen 欄目:開發(fā)技術(shù)

這篇文章主要介紹“C++中索引越界的解決方法”,在日常操作中,相信很多人在C++中索引越界的解決方法問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”C++中索引越界的解決方法”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

目錄
  • 1. 動態(tài)數(shù)組

  • 2.靜態(tài)數(shù)組

避免"索引越界"錯誤的規(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是空的,對應(yīng)的size()為0,
    //并且開始添加元素時,在長度達到n之前,不會出現(xiàn)導(dǎo)致速度降低的容量增長現(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;
}

到此,關(guān)于“C++中索引越界的解決方法”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI