废话不多说了,直接给大家上关键代码了。
1
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
|
#pragma once
#include <assert.h>
template < class T>
class SeqList
{
public :
SeqList()
:_a(NULL)
,_size(1)
,_capacity(1)
{}
SeqList(T* a, size_t size)
:_a( new T[size])
,_size(size)
,_capacity(size)
{
for ( size_t i = 0; i < _size; ++i)
{
_a[i] = a[i];
}
}
//拷贝构造函数常规写法
/*SeqList(const SeqList<T>& s)
:_a(new T[s._size])
,_size(s._size)
,_capacity(s._capacity)
{
for (size_t i = 0; i < _size; ++i)
_a[i] = s._a[i];
}*/
//拷贝构造函数现代写法
SeqList( const SeqList<T>& s)
:_a(NULL)
{
SeqList<T> tmp(s._a, s._size);
swap(_a, tmp._a);
_size = s._size;
_capacity = s._capacity;
}
~SeqList()
{
if (_a)
delete [] _a;
}
//赋值运算符重载常规写法
SeqList<T>& operator=( const SeqList<T>& s)
{
if ( this != &s)
{
T* tmp = new T[s._size];
for ( size_t i = 0; i < s._size; ++i)
{
tmp[i] = s._a[i];
}
delete [] _a;
_a = tmp;
_size = s._size;
_capacity = s._capacity;
}
return * this ;
}
//赋值运算符重载现代写法
/*SeqList<T>& operator=(SeqList<T> s)
{
if (this != &s)
{
swap(_a, s._a);
_size = s._size;
_capacity = s._capacity;
}
return *this;
}*/
public :
void Print()
{
for ( size_t i = 0; i < _size; ++i)
{
cout<<_a[i]<< " " ;
}
cout<<endl;
}
void PushBack( const T& x)
{
_CheckCapacity();
_a[_size++] = x;
}
void PopBack()
{
assert (_size > 0);
--_size;
}
void Insert( int pos, const T& x)
{
assert (pos >= 0 && pos <= _size);
_CheckCapacity();
int iIndex = _size;
while (iIndex > pos) //int和size_t比较为什么不行?
{
_a[iIndex] = _a[iIndex-1];
--iIndex;
}
_a[iIndex] = x;
++_size;
}
void Erase( size_t pos)
{
assert (_size > 0 && pos < _size);
size_t index = pos;
while (index < _size-1)
{
_a[index] = _a[index+1];
++index;
}
--_size;
}
int Find( const T& x)
{
for ( size_t i = 0; i < _size; ++i)
{
if (_a[i] == x)
{
return i;
}
}
return -1;
}
T& operator[]( size_t index)
{
assert (index >= 0 && index < _size);
return _a[index];
}
void Reserve( size_t size) //保留空间,增容到size
{
_capacity = size;
_a = (T*) realloc (_a, _capacity * sizeof (T));
}
void Clear() //不释放空间
{
_size = 0;
}
void Size()
{
return _size;
}
protected :
void _CheckCapacity()
{
if (_size+1 > _capacity)
{
_capacity = _capacity*2;
_a = (T*) realloc (_a, _capacity * sizeof (T));
}
}
protected :
T* _a;
size_t _size;
size_t _capacity;
};
|
以上所述是小编给大家介绍的顺序表的C++实现方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!