Created
June 14, 2016 13:47
-
-
Save blippy/dea1283e07d22ebef41e04ff3f9ecb5e to your computer and use it in GitHub Desktop.
COBOL-style contraol breaks in C++
This file contains hidden or 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 <functional> | |
| #include <stdlib.h> | |
| #include <iostream> | |
| #include <vector> | |
| template <class T> | |
| class breaker { | |
| public: | |
| breaker(std::vector<T>& cont, std::function<bool (T,T)> same_grp) | |
| : c_cont (cont), idx (-1), c_same_grp (same_grp) | |
| { num = cont.size();} | |
| bool more() { idx++; return idx < num; } | |
| T get() { return c_cont[idx]; } | |
| bool first() { return idx == 0 || ! c_same_grp(c_cont[idx-1], c_cont[idx]); } | |
| bool last() { return idx +1 == num | !c_same_grp(c_cont[idx],c_cont[idx+1]);} | |
| int idx; | |
| int num; | |
| std::function<bool (T, T)> c_same_grp; | |
| private: | |
| std::vector<T>& c_cont; | |
| }; | |
| int main() | |
| { | |
| std::vector<int> v { 1 , 3, 5, 2, 4 , 3}; | |
| auto higher = [](int a, int b) { return a <= b;}; | |
| breaker<int> brk(v, higher); | |
| int total; | |
| while(brk.more()) { | |
| if(brk.first()) { total = 0; std::cout << "Starting group\n"; } | |
| std::cout << brk.get() << "\n" ; | |
| total += brk.get(); | |
| if(brk.last()) { std::cout << "Group total: " << total << "\n\n";} | |
| } | |
| return EXIT_SUCCESS; | |
| } |
Author
Author
It processes input, breaking it into groups. The grouping function is passed in as function: higher in this case. It might typically look up a field, but in this case, it assumes that numbers in ascending order are part of a group, and starts a new group if it encounter a lower number.
Output is:
Starting group
1
3
5
Group total: 9
Starting group
2
4
Group total: 6
Starting group
3
Group total: 3
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also discussed on Stackoverflow:
http://stackoverflow.com/questions/35674408/why-is-trying-to-store-a-pointer-to-function-ambiguous
"Why is trying to store a pointer to function ambiguous"