-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdynamicTable.cpp
68 lines (64 loc) · 1.29 KB
/
dynamicTable.cpp
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
#include <vector>
#include <iostream>
using namespace std;
class DynamicTable
{
private:
vector<int> table;
int it;
public:
float cost;
DynamicTable()
{
it = 0;
cost = 0;
}
int insert(int);
void print();
};
void DynamicTable::print()
{
cout << "Table content: ";
for (auto el : table)
cout << el << " ";
cout << endl;
}
int DynamicTable::insert(int x)
{
int n = table.size();
// cost = 0; //for testing cost of each operation
if (it == n)
{
table.resize(n * 2);
if (n == 0)
{
table.emplace_back(x);
it++;
cost++;
}
for (size_t i = 1; i <= it + 1 && n != 0; i++)
cost++;
}
if (n)
{
if (it != n)
cost++;
table[it++] = x;
}
cout << "cost: " << cost << endl;
return table.size();
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
DynamicTable t;
float n{0};
for (size_t i = 0; i < 5; i++, n++)
cout << "Table size after inserting " << i << " : " << t.insert(i) << endl;
cout << endl;
t.print();
cout << "Amortized cost = " << t.cost / n << endl;
return 0;
}