关于c++:C模拟实现简易vector容器模板类命名空间重载运算符

56次阅读

共计 924 个字符,预计需要花费 3 分钟才能阅读完成。

参考了这篇博客:C++ 实现 vector

练习模板类,命名空间,重载运算符的根底应用。加了个命名空间和对方括号的重载,使得能够通过索引拜访数据。

#include <iostream>

namespace Morpheus {

    template<typename T>
    class vector {
    private:
        T* _first;
        T* _last;
        T* _end;

    public:
        vector(int size = 5) {_first = new T[size];
            _last = _first;
            _end = _first + size;
        }
        ~vector() {
            delete _first;
            _first = nullptr;
            _last = nullptr;
            _end = nullptr;
        }
        bool isEmpty() {return _first == _last;}
        bool isFull() {return _last == _end;}
        int size() {return _last - _first;}
        void push_back(const T& x) {if (isFull()) {expand();
            }
            *_last++ = x;
        }
        void pop_back() {if (!isEmpty()) {_last--;}
        }
        T operator[](const int& i) {return _first[i];
        }

    private:
        void expand() {
            int len = _end - _first;
            T* temp = new T[2 * len];

            for (int i = 0; i < len; ++i) {temp[i] = _first[i];
            }

            delete[] _first;
            _first = temp;
            _last = _first + len;
            _end = _first + 2 * len;

        }
    };
}

int main() {
    Morpheus::vector<double> v;
    v.push_back(1.2);
    v.push_back(1.3);
    v.push_back(1.4);
    for (int i = 0; i < v.size(); ++i) {std::cout << v[i] << ",";
    }
    v.pop_back();
    v.pop_back();
    for (int i = 0; i < v.size(); ++i) {std::cout << v[i] << ",";
    }
}

正文完
 0