first commit
This commit is contained in:
commit
9bfa1e11fe
1 changed files with 1751 additions and 0 deletions
89
moving_container.h
Normal file
89
moving_container.h
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
#ifndef MOVING_CONTAINER
|
||||
#define MOVING_CONTAINER
|
||||
|
||||
|
||||
using ld = long double;
|
||||
|
||||
template<typename T> class average {
|
||||
struct info {
|
||||
info *next = nullptr;
|
||||
T data;
|
||||
};
|
||||
info *head = nullptr, *tail = nullptr, *curr = nullptr;
|
||||
ld avg = 0.0;
|
||||
unsigned int count = 0;
|
||||
unsigned int max_size = 10;
|
||||
|
||||
public:
|
||||
average(int max_size = 10) {
|
||||
this->max_size = max_size;
|
||||
}
|
||||
|
||||
~average() {
|
||||
curr = head;
|
||||
while(curr != nullptr) {
|
||||
info *now = curr;
|
||||
curr = curr->next;
|
||||
delete now;
|
||||
}
|
||||
}
|
||||
|
||||
unsigned int size() {
|
||||
return this->count;
|
||||
}
|
||||
|
||||
double get_average() {
|
||||
return this->avg;
|
||||
}
|
||||
|
||||
void recalculate_average() {
|
||||
curr = head;
|
||||
this->avg = 0;
|
||||
this->count = 0;
|
||||
while(curr != nullptr) {
|
||||
info *now = curr;
|
||||
auto t = now->data;
|
||||
curr = curr->next;
|
||||
count++;
|
||||
avg = ((avg) * (ld) (count - 1) / (ld )(count)) + ((ld)(t) / (ld) count);
|
||||
}
|
||||
}
|
||||
|
||||
void push_back(T t) {
|
||||
if(head == nullptr) {
|
||||
auto *i = new info();
|
||||
i->next = nullptr;
|
||||
i->data = t;
|
||||
head = i;
|
||||
tail = i;
|
||||
}
|
||||
else {
|
||||
info *i = new info();
|
||||
if(this->count == max_size) {
|
||||
T old_value;
|
||||
if(head->next) {
|
||||
auto *temp = head;
|
||||
head = head->next;
|
||||
old_value = temp->data;
|
||||
delete temp;
|
||||
}
|
||||
recalculate_average();
|
||||
tail->next = i;
|
||||
i->next = nullptr;
|
||||
i->data = t;
|
||||
tail = i;
|
||||
}
|
||||
tail->next = i;
|
||||
i->next = nullptr;
|
||||
i->data = t;
|
||||
tail = i;
|
||||
}
|
||||
count++;
|
||||
avg = ((avg) * (ld) (count - 1) / (ld )(count)) + ((ld)(t) / (ld) count);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
#endif
|
||||
Loading…
Reference in a new issue