-
Notifications
You must be signed in to change notification settings - Fork 3
/
02-buzzdb.cpp
63 lines (52 loc) · 1.47 KB
/
02-buzzdb.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
#include <iostream>
#include <map>
#include <vector>
#include <fstream>
#include <iostream>
// A "class" in C++ is a user-defined data type.
// It is a blueprint for creating objects of a particular type,
// providing initial values for state (member variables or fields),
// and implementations of behavior (member functions or methods)
class Tuple {
public:
int key;
int value;
};
class BuzzDB {
private:
// a map is an ordered key-value container
std::map<int, std::vector<int>> index;
public:
// a vector of Tuple structs acting as a table
std::vector<Tuple> table;
// insert function
void insert(int key, int value) {
Tuple newTuple = {key, value};
table.push_back(newTuple);
index[key].push_back(value);
}
// perform a SELECT ... GROUP BY ... SUM query
void selectGroupBySum() {
for (auto const& pair : index) { // for each unique key
int sum = 0;
for (auto const& value : pair.second) {
sum += value; // sum all values for the key
}
std::cout << "key: " << pair.first << ", sum: " << sum << '\n';
}
}
};
int main() {
BuzzDB db;
std::ifstream inputFile("output.txt");
if (!inputFile) {
std::cerr << "Unable to open file" << std::endl;
return 1;
}
int field1, field2;
while (inputFile >> field1 >> field2) {
db.insert(field1, field2);
}
db.selectGroupBySum();
return 0;
}