Boost 範例程式:共享記憶體 - 查詢

程式碼

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

#include <iostream>#include <iomanip>#include <string>#include <math.h>#include <chrono>#include <thread>#include <algorithm>#include <functional>#include <boost/algorithm/string.hpp>#include "TMEMFile.h"using namespace std; using namespace Emprogria; class Stock { private: typedef struct { unsigned char stockDate[10]; float stockOpen, stockHigh, stockLow, stockClose, stockVol, stockAdjClose; } MEM_STOCK; void Output(MEM_STOCK *data) { // 更換日期格式 data->stockDate[4] = '-'; data->stockDate[7] = '-'; std::cout << data->stockDate << '\t'; std::cout << std::setprecision(2) << std::fixed << data->stockOpen << '\t'; std::cout << std::setprecision(2) << std::fixed << data->stockHigh << '\t'; std::cout << std::setprecision(2) << std::fixed << data->stockLow << '\t'; std::cout << std::setprecision(2) << std::fixed << data->stockClose << '\t'; std::cout << std::setprecision(2) << std::fixed << data->stockVol << '\t'; std::cout << std::setprecision(2) << std::fixed << data->stockAdjClose << '\n'; } public: // 格式化輸出共享記憶體內資料 void Print(std::string stockDate) { TMEMFile *worker = new TMEMFile("STOCK", 0); size_t packs = worker->GetMemSize() / sizeof(MEM_STOCK); int pos[3] = {0, packs - 1, packs / 2}; // 二分搜尋法 while (pos[0] < pos[1] && pos[2] > 0) { MEM_STOCK *data = (MEM_STOCK*) worker->Get(pos[2] * sizeof(MEM_STOCK), sizeof(MEM_STOCK)); // 比較資料 int less = std::memcmp(data->stockDate, stockDate.c_str(), sizeof(char) * 10); if (!less) { this->Output(data); break; } if (less > 0) { // 資料範圍在上半部 if (pos[1] == pos[2]) { // 已查過此資料 break; } pos[1] = pos[2]; } else { // 資料範圍在下半部 if (pos[0] == pos[2]) { // 已查過此資料 break; } pos[0] = pos[2]; } pos[2] = pos[0] + (pos[1] - pos[0]) / 2; } // 循序搜尋法// for (int i=0; i<packs; i++) {// MEM_STOCK *data = (MEM_STOCK*) worker->Get(i * sizeof(MEM_STOCK),// sizeof(MEM_STOCK));//// int less = std::memcmp(data->stockDate, stockDate.c_str(),// sizeof(char) * 10);//// if (!less) {// this->Output(data);// break;// }// } delete worker; } }; // 主程式int main(int argc, char* argv[]) { std::string stockDate = "2016/09/30"; Stock *worker = new Stock(); if (argc > 1) { stockDate = boost::replace_all_copy(std::string(argv[1]), "-", "/"); } worker->Print(stockDate); delete worker; return 0; }