跳到正文

个人记录

手写vector

chenbs约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月16日
更新
2025年12月16日
篇幅
约 2 分钟

版本

  1. v1当前

手写vector,经过测试比 std::vector 快

C++
template<typename T>class cbsvector {
	private:
		T *head, *now, *tail;
	public:
		cbsvector() noexcept {
			head = tail = (T*)malloc(sizeof(T));
			now = head-1;
		}
		explicit cbsvector(int size, T val=0) {
			head=(T*)malloc(sizeof(T)*size), now=tail=head+size-1;
			for(T* i=head; i<=tail; i++) *i=val;
		}
		~cbsvector() {
			free(head);
		}
		inline void push_back(T x) noexcept {
			if(now == tail) {
				int size = (tail-head+1)<<1;

				T *p = (T*)malloc(sizeof(T)*size);
				memcpy(p,head,sizeof(T)*(size>>1));
				free(head);

				head=p, tail=p+size-1, *(now=p+(size>>1))=x;
			} else *(++now) = x;
		}
		inline void pop_back() noexcept {
			--now;
		}
		inline T& back() const noexcept {
			return *now;
		}
		inline void clear() noexcept {
			now = head-1;
		}
		inline size_t size() const noexcept {
			return now-head+1;
		}
		inline T* begin() const noexcept {
			return head;
		}
		inline T* end() const noexcept {
			return now+1;
		}
		inline T& operator [] (int i) noexcept {
			return *(head+i);
		}
		inline const T& operator [] (int i) const noexcept {
			return *(head+i);
		}
};
原文