簡(jiǎn)版 容器vector 實(shí)現(xiàn)
vector為我們提供了可伸縮的順序存儲(chǔ)容器,在順序和隨機(jī)存儲(chǔ)方面效率很高
實(shí)現(xiàn)vector的關(guān)鍵在于實(shí)現(xiàn)內(nèi)存分配和對(duì)象構(gòu)造的分離,一般來講我們直接用new來構(gòu)造對(duì)象就經(jīng)歷了這兩個(gè)過程,而實(shí)現(xiàn)vector就需要我們先申請(qǐng)請(qǐng)到一片連續(xù)的內(nèi)存區(qū)域,然后在需要時(shí)在改內(nèi)存上構(gòu)造對(duì)象。這里用到allocator模板類
該類內(nèi)部封裝了如下方法:
template<typename elm>
class allocator
{
elm *allocate(size_t n) //分配n個(gè)對(duì)象存儲(chǔ)空間
void construct(elm* p,size_t n) //在以p為開始的內(nèi)存上構(gòu)造n個(gè)對(duì)象
void destroy(elm* p) //銷毀對(duì)象
void deallocate(elm*p,size_t n) //釋放從p開始的n個(gè)對(duì)象內(nèi)存
有了這些就足夠了,一下就是簡(jiǎn)版Vector實(shí)現(xiàn)LyVector
1
#include "stdafx.h"
2
#include "memory"
3
template <typename elmType>
4
class LyVector
5

{
6
private:
7
elmType* _first;
8
elmType* _last;
9
elmType* _end;
10
allocator<elmType> _alc;
11
public:
12
typedef typename elmType valueType;
13
LyVector():
14
_first(0),_last(0),_end(0)
{};
15
bool push_back(const elmType &t)
16
{
17
if (_last==_end)
18
{
19
size_t size=_last-_first;
20
21
size_t capacity=2*size;
22
if (capacity==0)
23
{
24
capacity=2;
25
}
26
//創(chuàng)建新的存儲(chǔ)區(qū)域并賦值
27
elmType* newElm=_alc.allocate(capacity);
28
if (newElm==NULL)
29
{
30
return false;
31
}
32
uninitialized_copy(_first,_last,newElm);
33
//刪除就有存儲(chǔ)區(qū)
34
for(;_first!=_last;)
35
_alc.destroy(--_last);
36
_alc.deallocate(_first,size);
37
_first=newElm;
38
_last=newElm+size;
39
_end=newElm+capacity;
40
}
41
_alc.construct(_last++,t);
42
return true;
43
}
44
void popBack()
45
{
46
if (size()==0)
47
{
48
_DEBUG_ERROR("No element fount");
49
return;
50
}
51
_alc.destroy(--_last);
52
}
53
54
size_t size()
55
{
56
return _last-_first;
57
}
58
size_t capacity()
59
{
60
return _end-_first;
61
}
62
63
elmType* operator[](size_t pos)
64
{
65
if (pos>=size())
66
{
67
_DEBUG_ERROR("out of range");
68
return NULL;
69
}
70
return _first+pos;
71
}
72
73
74
friend ostream& operator<<(ostream &o,const LyVector &im)
75
{
76
for (LyVector::valueType * first=im._first;first!=im._last;first++)
77
{
78
o<<*first<<endl;
79
}
80
return o;
81
}
82
};

2

3

4

5



6

7

8

9

10

11

12

13

14



15

16



17

18



19

20

21

22

23



24

25

26

27

28

29



30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45



46

47



48

49

50

51

52

53

54

55



56

57

58

59



60

61

62

63

64



65

66



67

68

69

70

71

72

73

74

75



76

77



78

79

80

81

82

從實(shí)現(xiàn)看來,我覺得在使用vector,有以下幾點(diǎn)注意:
1. 最好為所存儲(chǔ)對(duì)象實(shí)現(xiàn)拷貝構(gòu)造函數(shù),不然在重新分配存儲(chǔ)空間時(shí)可能會(huì)產(chǎn)生內(nèi)存訪問違規(guī)問題,原因是對(duì)象在存入vector和在vecotr重新構(gòu)造是都會(huì)調(diào)用拷貝構(gòu)造函數(shù)
2. 對(duì)象存入是會(huì)在制定位置產(chǎn)生新的對(duì)象,不必?fù)?dān)心原對(duì)象生存期
posted on 2009-08-12 15:46 pear_li 閱讀(2501) 評(píng)論(0) 編輯 收藏 引用 所屬分類: C++