fork(2) download
  1. #include <iostream>
  2. #include <iterator>
  3. #include <fstream>
  4. #include <string>
  5. #include <boost/date_time/gregorian/gregorian.hpp>
  6.  
  7. struct Log
  8. {
  9. typedef boost::gregorian::date Date;
  10. Date date;
  11. int info;
  12. };
  13.  
  14. std::ostream& operator <<(std::ostream& os, const Log& l)
  15. {
  16. return os << l.date << " " << l.info;
  17. }
  18.  
  19. std::istream& operator >>(std::istream& is, Log& l)
  20. {
  21. return is >> l.date >> l.info;
  22. }
  23.  
  24. Log LowerBound(std::istream& os, Log::Date d)
  25. {
  26. using namespace std;
  27. os.seekg(0, std::ios::end);
  28. streamoff length = os.tellg();
  29. streampos current = 0;
  30. Log l;
  31. for(; length > 0;)
  32. {
  33. streamoff half = length / 2;
  34. streampos mid = current + half;
  35. os.seekg(mid);
  36.  
  37. string line;
  38. getline(os, line);
  39.  
  40. if (!(os >> l.date >> l.info))
  41. throw std::runtime_error("bad log format");
  42. if (l.date < d)
  43. {
  44. mid += 1;
  45. current = mid;
  46. length = length - half + 1;
  47. }
  48. else
  49. length = half;
  50. }
  51. return l;
  52. }
  53.  
  54. template<typename OutIter>
  55. void ReadLogsInRange(
  56. std::istream& logStream, Log::Date from, Log::Date to, OutIter out)
  57. {
  58. using namespace std;
  59.  
  60. Log l = LowerBound(logStream, from);
  61. *out++ = l;
  62. // Upper Bound
  63. while(logStream >> l && l.date < to)
  64. *out++ = l;
  65. }
  66.  
  67.  
  68. int main()
  69. {
  70. using namespace boost::gregorian;
  71.  
  72. // Create log
  73. Log l;
  74. l.date = Log::Date(2011, Sep, 1);
  75. l.info = 1;
  76.  
  77. std::stringstream log;
  78. for(int i = 0; i < 1000; ++i)
  79. {
  80. log << l << std::endl;
  81. l.date += days(1);
  82. ++l.info;
  83. }
  84.  
  85. // Read the log
  86. std::vector<Log> range;
  87. ReadLogsInRange(log,
  88. date(2011, Sep, 9), date(2011, Sep, 12),
  89. std::back_inserter(range));
  90.  
  91. std::copy(range.begin(), range.end(),
  92. std::ostream_iterator<Log>(std::cout, "\n"));
  93. }
Success #stdin #stdout 0s 2932KB
stdin
Standard input is empty
stdout
2011-Sep-09 9
2011-Sep-10 10
2011-Sep-11 11