当c 中的矢量容器过载[]运算符时,我对未定义的索引返回什么

What do I return for undefined index when overloading [] operator for vector container in C++?

本文关键字:运算符 未定义 什么 返回 索引      更新时间:2023-10-16

我刚刚开始在C 中实现一个基本的向量容器。它远非完成,但看起来像这样:

using namespace std;
typedef unsigned  long long int bigInt;
namespace stl2{
    template<class T>
    class vector{
    private:
        bigInt l;
        bigInt cap;
        T* arr;
    public:
        vector(){
            cap = 0;
            l = 0;
        }
        ~vector(){
            if (cap > 0) delete[] arr;
        }
        vector(bigInt size){
            cap = size;
            l = size;
            arr = new T[size];
        }
        vector(bigInt size, const T& def) : vector(size){
            for (bigInt i = 0; i < size; i++){
                arr[i] = def;
            }
        }
        bigInt size(){
            return l;
        }
        bigInt length(){
            return l;
        }
        bigInt capacity(){
            return cap;
        }
        void resize(bigInt size){
            if (size < cap) return;
            l = size;
            cap = size;
        }
        void push_back(const T& data){
            // Check if vector is full
            if (l == cap) {
                //Copy all elements of this vector to another
                if (cap == 0)
                    cap = 1;
                else
                    cap *= 2;
                T* temp = new T[cap];
                for (int i = 0; i < l; i++){
                    temp[i] = arr[i];
                }
                delete[] arr;
                arr = temp;
            }
            arr[l] = data;
            l++;
        }
        //Operators
        T& operator[](bigInt index){
            if (index < cap)
                return arr[index];
        }
    };
}

所以我对[]运算符有问题。我知道如果索引&lt;容量,我可以返回ARR [索引]。但是,如果索引大于或等于>容量,我该返回什么?由于我正在返回对元素的引用,因此我无法返回一个值。

std::vector在使用无效索引的at()时会引发异常,您可以执行相同的操作。

std::vectoroperator[]不执行界限检查,使用无效的索引是未定义的行为。