-
Notifications
You must be signed in to change notification settings - Fork 0
/
trs33.c
160 lines (127 loc) · 2.66 KB
/
trs33.c
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
159
160
#include <iostream>
#include <exception>
template <typename T>
class Array
{
template <typename U>
friend void swap(Array<U>&, Array<U>&);
public:
typedef std::size_t size_type;
typedef T value_type;
typedef value_type& reference;
typedef const value_type& const_reference;
//c-like iterator
typedef T* iterator;
Array() :
_data(nullptr),
_size(0),
_capacity(0)
{
}
Array(const Array& other)
{
_alloc(other.capacity());
std::copy(_data, other._data, other.size());
std::copy(_size, other.size());
std::copy(_capacity, other.capacity());
}
Array& operator=(Array other)
{
other.swap(*this);
return *this;
}
~Array()
{
_dealloc();
}
void swap(Array& other)
{
std::swap(_data, other._data);
std::swap(_size, other._size);
std::swap(_capacity, other._capacity);
}
size_type size() const
{
return _size;
}
size_type capacity() const
{
return _capacity;
}
void push_back(const value_type& value)
{
if (_size == 0)
{
_alloc(1);
_capacity = 1;
}
else if (_size == _capacity)
{
_alloc(_capacity * 2);
_capacity *= 2;
}
_data[_size++] = value;
}
reference at(size_type i)
{
if (i >= _size)
throw std::out_of_range();
return _data[i];
}
const_reference at(size_type i) const
{
if (i >= _size)
throw std::out_of_range();
return _data[i];
}
reference operator[](size_type i)
{
return _data[i];
}
const_reference operator[](size_type i) const
{
return _data[i];
}
iterator begin()
{
if (_size == 0)
return end();
return &_data[0];
}
iterator end()
{
if (_capacity == 0)
return nullptr;
return &_data[_size];
}
private:
value_type *_data;
size_type _size;
size_type _capacity;
void _alloc(size_type count)
{
if (!(_data = (value_type*)realloc(_data, count * sizeof(value_type))))
{
throw std::bad_alloc();
}
}
void _dealloc()
{
free(_data);
}
};
int main()
{
int count = 10;
Array<int> array;
for (int i = 0; i < count; ++i)
{
array.push_back(i);
}
for (Array<int>::iterator it = array.begin(); it != array.end(); ++it)
{
std::cout << *it << std::endl;
}
std::getchar();
return 0;
}