简体   繁体   中英

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

I just started to implement a basic vector container in C++. It is far from completion, but it looks like this:

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];
        }
    };
}

So I have a problem with the [] operator. I know that if the index < capacity, I can return arr[index]. But what do I return if the index is greater than or equal to the capacity ? Since I am returning a reference to the element, I cannot return a value.

The std::vector throws an exception when using at() with an invalid index, you could do the same.

The operator[] of std::vector however does not perform bounds checking, using an invalid index is undefined behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM