自己動手實現vector

2021-09-12 07:07:41 字數 2407 閱讀 3564

有了實現string的基礎,在加上一點點模板的知識,就可以自己動手實現乙個vector了。下面是我實現的**,比較簡單。有點犯懶了,講解以後再寫吧!

#ifndef my_vector_h

#define my_vectoe_h

#include

typedef

unsigned

int size_t;

template < class t>

class vector

;template

vector::

vector()

template

vector::

vector

(int s,

const t& a)

_size = s;

_capacity =1;

while

(_capacity < _size)

_buf = new t[_capacity]

;for

(size_t i =

0; i < _size; i++)}

template

vector::

vector

(const vector

& a)

}template

vector::

~vector()

template

size_t vector::

size()

const

template

size_t vector::

capacity()

const

template

size_t vector::

max_capacity()

const

template

t& vector

::operator(

int index)

template

void vector::

push_back

(const t& val)

else

if(_size == _max_capacity)

_capacity *=2

;if(_capacity >= _max_capacity)

t * tmp = new t[_capacity]

;for

(size_t i =

0; i < _size; i++

) tmp[_size]

= val;

_size++

; delete[

] _buf;

_buf = tmp;

}template

void vector::

pop_back()

template

bool vector::

empty()

const

return false;

}// 迭代器的實現

template

typename vector

::iterator vector::

begin()

const

template

typename vector

::iterator vector::

end(

)const

template

vector

& vector

::operator=

(const vector

& a)

delete[

] _buf;

_size = a._size;

_capacity = a._capacity;

_buf = new t[_capacity]

;for

(size_t i =

0; i < _size; i++

)return

*this;

}#endif

測試**:

#include

#include

"myvector.h"

#include

using namespace std;

intmain()

b = a;

for(vector

::iterator it = b.

begin()

; it != b.

end(

); it++

)return0;

}

執行結果:

$ .

/a.out

hello

hello

hello

自己動手實現redux 一

訂閱事件,返回乙個取消訂閱函式 let subscribe cb let dispatch action return export default createstore 當我們使用redux時,首先需要使用redux的createstore並且傳入reducer來建立我們的store impor...

C 自己動手實現Spy (一)

intptr hwnd win32.windowfrompoint cursor.position 最關鍵的一句 if oldwnd intptr.zero oldwnd hwnd if hwnd intptr.zero else hwnd.toint32 tostring textbox3.tex...

自己動手簡單實現CountDownLatch

在使用執行緒池的過程中,如何判斷所有提交的任務都已經執行完畢了呢?使用jdk自帶的countdownlatch,可以輕鬆實現這一需求 public class countdownlatchtest catch interruptedexception e executorservice.shutdo...