-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathringpuffer.cpp
More file actions
135 lines (109 loc) · 2.12 KB
/
ringpuffer.cpp
File metadata and controls
135 lines (109 loc) · 2.12 KB
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
#include <iostream>
using namespace std;
class Ringpuffer {
public:
bool push(double newelement);
double pop();
double element(int number) const;
Ringpuffer(int size);
~Ringpuffer();
private:
int NumberOfElements;
int ElementsInUse;
double* ptr;
double* pushptr;
double* popptr;
};
Ringpuffer::Ringpuffer(int size):NumberOfElements(size) {
ptr=new double[NumberOfElements];
pushptr=ptr;
popptr=ptr;
ElementsInUse=0;
}
bool Ringpuffer::push(double newelement)
{
if (ElementsInUse>=NumberOfElements) //Zu viele Elemente
{
return 0;
}
*pushptr=newelement; //Element schreiben
if (pushptr==ptr+NumberOfElements-1) //Überprüfen, ob letztes Element
{
pushptr=ptr; //Zurück zum 1. Element
}
else
{
pushptr++; //Weiterspringen falls nicht am Ende
}
ElementsInUse++; //Erhöhe Zahl der Elemente
return 1;
}
double Ringpuffer::pop()
{
if (ElementsInUse==0)
{
return 0;
}
double returnvalue=*popptr;
if (popptr==ptr+NumberOfElements-1) //Überprüfen, ob letztes Element
{
popptr=ptr; //Zurück zum 1. Element
}
else
{
popptr++; //Weiterspringen falls nicht am Ende
}
ElementsInUse--; //Senke Zahl der Elemente
return returnvalue;
}
double Ringpuffer::element(int number) const
{
if ((number<0)||(number>=NumberOfElements))
{
return 0;
}
return *(ptr+number);
}
Ringpuffer::~Ringpuffer() {
delete[] ptr;
}
int main()
{
int size;
cout << "Bitte Groesse des Puffers angeben: " << flush;
cin >> size;
Ringpuffer puffer(size);
int s=0;
while (s!=4)
{
cout << "push=>1 pop=>2 read=>3 quit=>4 " << flush;
cin >> s;
if (s==1) //push
{
double add;
cout << "Zahl eingeben: " << flush;
cin >> add;
if (puffer.push(add)==1)
{
cout << "Zahl erfolgreich hinzugefuegt" << endl;
}
else
{
cout << "Zahl konnte nicht hinzugefuegt werden" << endl;
}
}
if (s==2) // pop
{
cout << "Die Zahl ist " << puffer.pop() << " und wurde geloescht" << endl;
}
if (s==3) //read
{
int n;
cout << "Element eingeben (zwischen 0 und " << size-1 << "): " << flush;
cin >> n;
cout << "Der Zahl ist " << puffer.element(n) << endl;
}
cout << endl;
}
return 0;
}