zoukankan      html  css  js  c++  java
  • 数据结构与算法-C++实现动态变长数组

    一个简单至极的变长数组,仅仅是在原生数组中添加了自动变长功能

    参考STL中vector的实现,每次下标越界,就将数组容量扩大一倍。

    1. 申请新的空间,是原长度的二倍
    2. 从原内存复制所有内容到新内存
    3. 释放原内存
    /*
    	Author:  trialley
    	Date:    2019-7-26
    	Licence: MIT
    */
    
    #pragma once
    #include<cstring>		//memset,memcpy
    #include<cstdlib>		//malloc
    
    template<typename T>
    class darray{
    	private:
    		T* head;		//the array head pointer
    		int length;		//the length of array
    	public:
    		darray(int n=100){
    			length=n;
    			head=(T*)malloc(sizeof(T)*length);
    			memset(head,0,length);
    		}
    		
    		// "&" is a must !
    		T& operator [](int i){
    			if(i>length){
    				exlength();
    				return head[i];
    			}
    			return head[i];
    		}
    		exlength(){
    			int nlength=2*length;
    			T* temp=head;
    			head=(T*)malloc(sizeof(T)*nlength);
    			memset(head,0,nlength);
    			memcpy(head,temp,length);
    			length=nlength;
    		}
    };
    
    文有疏漏,请大家批评指正!
  • 相关阅读:
    C#调用webservice
    C#调用java方法踩坑记
    GitHub
    oracle之在java中调用
    oracle之数据恢复(delete误删)
    word之高级
    word之个人设置
    word之常用功能
    word
    git之摘抄
  • 原文地址:https://www.cnblogs.com/trialley/p/11248890.html
Copyright © 2011-2022 走看看