@lemegeton
2931 / 1360 / 136
Регистрация: 29.11.2010
Сообщений: 2,725
|
08.04.2011, 01:54
|
|
Без периметра.
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
| #include <cstdlib>
#include <cstdio>
#include <ctime>
struct Point {
int x;
int y;
Point() : x(0), y(0) {}
Point(int x_, int y_) : x(x_), y(y_) {}
};
bool operator==(const Point& a, const Point& b) {
return ((a.x == b.x) && (a.y == b.y));
}
template<typename Tp_>
class Set {
public:
Set() : size_(0), capacity_(0), recap_(10), data_(NULL) {}
Set(const Set& other) : data_(NULL) {
CopyFrom(other);
}
~Set() { delete [] data_; }
void Recap(size_t new_capacity) {
Tp_* new_data = new Tp_[new_capacity];
size_t new_size = ((new_capacity < size_) ? new_capacity : size_);
for (int i = 0; i < new_size; ++i)
new_data[i] = data_[i];
delete [] data_;
size_ = new_size;
capacity_ = new_capacity;
data_ = new_data;
}
bool Has(const Tp_& value) const {
return IndexOf(value) != -1;
}
void Add(const Tp_& value) {
if (!Has(value)) {
if (size_ >= capacity_)
Recap(capacity_ + recap_);
data_[size_++] = value;
}
}
void Clear() {
delete [] data_;
data_ = NULL;
size_ = capacity_ = NULL;
}
size_t Size() const {
return size_;
}
Tp_ &operator[](size_t i) const {
return data_[i];
}
void Remove(const Tp_& value) {
int index = IndexOf(value);
if (index != -1)
data_[index] = data_[--size_];
}
void CopyFrom(const Set& other) {
Clear();
size_ = other.size_;
capacity_ = other.capacity_;
recap_ = other.recap_;
data_ = new Tp_[capacity_];
for (int i = 0; i < size_; ++i)
data_[i] = other.data_[i];
}
Set operator=(const Set &other) {
if (this == &other)
CopyFrom(other);
return this;
}
Set Union(const Set &other) {
Set result(other);
for (int i = 0; i < Size(); ++i)
result.Add((*this)[i]);
return result;
}
Set Intersection(const Set &other) {
Set result;
for (int i = 0; i < Size(); ++i)
if (other.Has((*this)[i]))
result.Add((*this)[i]);
return result;
}
private:
size_t size_;
size_t capacity_;
size_t recap_;
Tp_* data_;
int IndexOf(const Tp_& value) const {
for (int i = 0; i < size_; ++i)
if (data_[i] == value)
return i;
return -1;
}
};
void PrintSet(const Set<Point> &points) {
for (int i = 0; i < points.Size(); ++i)
printf("(%d, %d) ", points[i].x, points[i].y);
printf("\n");
}
int main(int argc, char *argv[]) {
srand(time(NULL));
Set<Point> a, b;
for (int i = 0; i < 15; ++i) {
a.Add(Point(rand() % 5, rand() % 5));
b.Add(Point(rand() % 5, rand() % 5));
}
PrintSet(a);
PrintSet(b);
PrintSet(a.Union(b));
PrintSet(a.Intersection(b));
} |
|
1
|