Mercurial > repos > yufei-luo > s_mart
comparison SMART/Java/Python/Cpp/table.hpp @ 18:94ab73e8a190
Uploaded
author | m-zytnicki |
---|---|
date | Mon, 29 Apr 2013 03:20:15 -0400 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
17:b0e8584489e6 | 18:94ab73e8a190 |
---|---|
1 #ifndef TABLE_HPP | |
2 #define TABLE_HPP | |
3 | |
4 #include <iostream> | |
5 #include <fstream> | |
6 #include <string> | |
7 #include <stdio.h> | |
8 using namespace std; | |
9 | |
10 typedef unsigned int Value; | |
11 static const unsigned int SENTINEL = -1; | |
12 | |
13 class Table { | |
14 private: | |
15 int sentinel; | |
16 Value *values; | |
17 | |
18 public: | |
19 string fileName; | |
20 unsigned int width; | |
21 unsigned int height; | |
22 fstream file; | |
23 | |
24 Table (string fileName, unsigned int width, unsigned int height): sentinel(-1), fileName(fileName), width(width), height(height) { | |
25 file.open(fileName.c_str(), ios::out | ios::in | ios::binary); | |
26 Value v = 0; | |
27 for (unsigned int i = 0; i < width * height; i++) { | |
28 writeHere(v); | |
29 } | |
30 file.flush(); | |
31 values = new Value[width]; | |
32 } | |
33 | |
34 ~Table () { | |
35 delete[] values; | |
36 } | |
37 | |
38 void moveTo (unsigned int col, unsigned int line) { | |
39 if (col == SENTINEL) { | |
40 sentinel = line; | |
41 } | |
42 else { | |
43 sentinel = -1; | |
44 file.seekp((col * width + line) * sizeof(Value)); | |
45 } | |
46 } | |
47 | |
48 void write (Value v, unsigned int col, unsigned int line) { | |
49 moveTo(col, line); | |
50 writeHere(v); | |
51 } | |
52 | |
53 void writeHere(Value v) { | |
54 if (sentinel >= 0) | |
55 values[sentinel] = v; | |
56 else | |
57 file.write(reinterpret_cast<const char*>(&v), sizeof(Value)); | |
58 } | |
59 | |
60 | |
61 Value read (unsigned int col, unsigned int line) { | |
62 moveTo(col, line); | |
63 return readHere(); | |
64 } | |
65 | |
66 Value readHere () { | |
67 if (sentinel >= 0) { | |
68 return values[sentinel]; | |
69 } | |
70 else { | |
71 Value v; | |
72 file.read(reinterpret_cast<char*>(&v), sizeof(Value)); | |
73 return v; | |
74 } | |
75 } | |
76 | |
77 void destroy () { | |
78 file.close(); | |
79 remove(fileName.c_str()); | |
80 } | |
81 | |
82 }; | |
83 | |
84 #endif |