Created
March 8, 2016 12:19
-
-
Save KrzaQ/027adc41aa6cdfd8dd4b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cassert> | |
#include <climits> | |
#include <csetjmp> | |
#include <cstdlib> | |
#include <cstring> | |
#include <cctype> | |
#include <algorithm> | |
#include <array> | |
#include <atomic> | |
#include <chrono> | |
#include <deque> | |
#include <fstream> | |
#include <iomanip> | |
#include <iostream> | |
#include <iterator> | |
#include <list> | |
#include <map> | |
#include <memory> | |
#include <mutex> | |
#include <random> | |
#include <regex> | |
#include <set> | |
#include <sstream> | |
#include <string> | |
#include <utility> | |
#include <vector> | |
#include <thread> | |
#include <type_traits> | |
#include <typeinfo> | |
#include <tuple> | |
#include <unordered_set> | |
using namespace std; | |
constexpr int Width = 60; | |
#define DBG(x) { cout << left << setw(Width) << #x << boolalpha << (x) << endl; } | |
#define DBG_CONT(x) { cout << left << setw(Width) << #x; for(auto const& _name : (x)) \ | |
cout << boolalpha << _name << " "; cout << endl; } | |
#define BARK cout << __PRETTY_FUNCTION__ << endl; | |
template<typename State> | |
class Loop | |
{ | |
enum ReturnValue{ | |
FirstIteration = 0, | |
ContinueLoop = 1, | |
BreakLoop = 2 | |
}; | |
public: | |
Loop(State& s) : state_(s) {} | |
template<typename Body, typename Condition> | |
void execute(Body b, Condition c){ | |
switch(setjmp(loopBuffer_)){ | |
case FirstIteration: | |
case ContinueLoop: | |
if(!c(state_)){ | |
longjmp(loopBuffer_, BreakLoop); | |
}else{ | |
b(state_); | |
longjmp(loopBuffer_, ContinueLoop); | |
} | |
} | |
} | |
private: | |
State& state_; | |
std::jmp_buf loopBuffer_; | |
}; | |
struct AveragingLoopState | |
{ | |
int lastRead; | |
int count; | |
int sum; | |
}; | |
void loopBody(AveragingLoopState& s){ | |
if(!(cin >> s.lastRead)){ s.lastRead = 0; } | |
if(s.lastRead){ | |
++s.count; | |
s.sum += s.lastRead; | |
} | |
} | |
bool loopCondition(AveragingLoopState const& s){ | |
return s.lastRead; | |
} | |
int main() | |
{ | |
AveragingLoopState s; | |
s.lastRead = -1; | |
s.count = 0; | |
s.sum = 0; | |
Loop<AveragingLoopState> loop(s); | |
loop.execute(&loopBody, &loopCondition); | |
cout << "Srednia to: " << static_cast<double>(s.sum) / s.count << endl; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment