include iostream include stdio template class TypeOfElement class MyVe

 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
#include <iostream>
#include <stdio.h>
template <class TypeOfElement>
class MyVector {
public:
MyVector (TypeOfElement inputArray[], int inLength) {
if (dataPointer) delete [] dataPointer;
dataPointer = new TypeOfElement [inLength];
for (int i = 0; i < inLength; i++) {
dataPointer[i] = inputArray[i];
}
capacity = length = inLength;
}
~MyVector () { if (dataPointer) delete [] dataPointer; }
void PushBack (TypeOfElement newElement) {
if (length == capacity) UpCapacity(length * 2);
dataPointer[length++] = newElement;
}
TypeOfElement &operator[] (int index) { return dataPointer[index]; };
bool IsEmpty () const { return (length == 0); };
int Length () const { return length; };
int Capacity () const { return capacity; };
private:
void UpCapacity (int newCapacity) {
TypeOfElement *newDataPointer = new TypeOfElement [newCapacity];
for (int i = 0; i < capacity; i++) {
newDataPointer[i] = dataPointer[i];
}
delete [] dataPointer;
dataPointer = newDataPointer;
capacity = newCapacity;
}
int length = 0;
int capacity = 0;
TypeOfElement *dataPointer = NULL;
};
using namespace std;
int main() {
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
MyVector<int> vec1();
vec1.PushBack(2);
MyVector<int> vec(a, 10);
cout << "array length: " << vec.Length() << "\n";
cout << "array capacity: " << vec.Capacity() << "\n";
for (int i = 0; i < vec.Length(); i++) {
cout << "vec[" << i << "]: " << vec[i] << "\n";
}
vec.PushBack(11); //размер массива увеличится в 2 раза и добавит элемент 11
cout << "array length: " << vec.Length() << "\n";
cout << "array capacity: " << vec.Capacity() << "\n";
for (int i = 0; i < vec.Length(); i++) {
cout << "vec[" << i << "]: " << vec[i] << "\n";
}
return 0;
}