欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2021年08月03日 16:36:09   作者:Welcom to LyAsano’s blog!  
本文主要介紹了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;
}

到此這篇關(guān)于C++索引越界的解決方法的文章就介紹到這了,更多相關(guān)C++索引越界內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • C++ 中dynamic_cast&lt;&gt;的使用方法小結(jié)

    C++ 中dynamic_cast&lt;&gt;的使用方法小結(jié)

    將一個基類對象指針(或引用)cast到繼承類指針,dynamic_cast會根據(jù)基類指針是否真正指向繼承類指針來做相應處理
    2013-03-03
  • VC對自定義資源加密解密(AES)的詳解

    VC對自定義資源加密解密(AES)的詳解

    本篇文章是對VC對自定義資源加密解密(AES)進行了詳細的分析介紹,需要的朋友參考下
    2013-06-06
  • 詳解C語言讀取文件求某一列的平均值

    詳解C語言讀取文件求某一列的平均值

    本文粗淺比較了C語言中常用的幾種讀取文件的函數(shù)的效率,并給出了幾段求取某列平均值的代碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多度進步
    2022-02-02
  • 基于C語言sprintf函數(shù)的深入理解

    基于C語言sprintf函數(shù)的深入理解

    本篇文章是對C語言中的sprintf函數(shù)進行了詳細的分析介紹,需要的朋友參考下
    2013-05-05
  • C++中 string 中的常用方法使用心得

    C++中 string 中的常用方法使用心得

    這篇文章主要介紹了C++中 string 中的常用方法使用心得,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-03-03
  • 一文帶你掌握C++中的繼承

    一文帶你掌握C++中的繼承

    繼承機制是面向?qū)ο蟪绦蛟O計使代碼可以復用的最重要的手段,它允許程序員在保持原有類特性的基礎(chǔ)上進行擴展,增加功能,本文詳解介紹了C++中的繼承,感興趣的同學可以借鑒一下
    2023-05-05
  • new和malloc的區(qū)別深入解析

    new和malloc的區(qū)別深入解析

    以下是分別是對new和malloc的區(qū)別進行了詳細的分析及介紹,需要的朋友可以過來參考下
    2013-09-09
  • C++讀取配置文件的示例代碼

    C++讀取配置文件的示例代碼

    這篇文章主要介紹了C++讀取配置文件的示例代碼,幫助大家更好的理解和學習C++開發(fā),感興趣的朋友可以了解下
    2020-08-08
  • C語言學習筆記之字符串間的那些事

    C語言學習筆記之字符串間的那些事

    字符串是C語言中最重要的數(shù)據(jù)類型之一,最近借助《C Primer Plus》一書來學習C中的常用字符串操作,在此作為筆記記錄,下面這篇文章主要給大家介紹了C語言學習筆記之字符串間的那些事,需要的朋友可以參考下
    2022-04-04
  • C/C++中使用局部/全局變量初始值或默認值問題

    C/C++中使用局部/全局變量初始值或默認值問題

    這篇文章主要介紹了C/C++中使用局部/全局變量初始值或默認值問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-08-08

最新評論