C++: Vector bounds

后端 未结 4 1514
北海茫月
北海茫月 2020-12-11 01:40

I am coming from Java and learning C++ in the moment. I am using Stroustrup\'s Progamming Principles and Practice of Using C++. I am working with vectors now. On page 117 he

4条回答
  •  无人及你
    2020-12-11 02:04

    I hoped that vector's "operator[]" would check boundary as "at()" does, because I'm not so careful. :-)

    One way would inherit vector class and override operator[] to call at() so that one can use more readable "[]" and no need to replace all "[]" to "at()". You can also define the inherited vector (ex:safer_vector) as normal vector. The code will be like this(in C++11, llvm3.5 of Xcode 5).

    #include 
    
    using namespace std;
    
    template  >
    class safer_vector:public vector<_Tp, _Allocator>{
    private:
        typedef __vector_base<_Tp, _Allocator>           __base;
    public:
        typedef _Tp                                      value_type;
        typedef _Allocator                               allocator_type;
        typedef typename __base::reference               reference;
        typedef typename __base::const_reference         const_reference;
        typedef typename __base::size_type               size_type;
    public:
    
        reference operator[](size_type __n){
            return this->at(__n);
        };
    
        safer_vector(_Tp val):vector<_Tp, _Allocator>(val){;};
        safer_vector(_Tp val, const_reference __x):vector<_Tp, _Allocator>(val,__x){;};
        safer_vector(initializer_list __il):vector<_Tp, _Allocator>(__il){;}
        template 
        safer_vector(_Iterator __first, _Iterator __last):vector<_Tp,_Allocator>(__first, __last){;};
        // If C++11 Constructor inheritence is supported
        // using vector<_Tp, _Allocator>::vector;
    };
    #define safer_vector vector
    

提交回复
热议问题