Commit 8e894b70fa4f07dd2bb0f84c361364ae1697d23b

Authored by Grzegorz Jabłoński
1 parent 121e73b8

Added foreach example

examples09/02-iterator/foreach.cpp 0 → 100644
  1 +#include <stddef.h>
  2 +#include <iostream>
  3 +
  4 +class Iterator;
  5 +
  6 +class Collection
  7 +{
  8 + static const size_t size = 10;
  9 + int data[size];
  10 + using iterator = Iterator;
  11 + friend class Iterator;
  12 +public:
  13 + Iterator begin();
  14 + Iterator end();
  15 +};
  16 +
  17 +class Iterator
  18 +{
  19 + int i;
  20 + Collection* c;
  21 +public:
  22 + Iterator(int ii, Collection* cc) : i(ii), c(cc){};
  23 + int& operator *()
  24 + {
  25 + return c->data[i];
  26 + }
  27 + Iterator& operator++()
  28 + {
  29 + ++i;
  30 + return *this;
  31 + }
  32 + bool operator!=(const Iterator& o)
  33 + {
  34 + return i != o.i;
  35 + }
  36 +
  37 +};
  38 +
  39 +Iterator Collection::begin()
  40 +{
  41 + return Iterator(0,this);
  42 +}
  43 +
  44 +Iterator Collection::end()
  45 +{
  46 + return Iterator(Collection::size-1,this);
  47 +}
  48 +
  49 +int main()
  50 +{
  51 +Collection c;
  52 +
  53 +int a = 3;
  54 +
  55 +for(auto& i: c)
  56 + i = a++;
  57 +
  58 +for(auto i: c)
  59 + std::cout << i << std::endl;
  60 +
  61 +}
  62 +
  63 +
0 64 \ No newline at end of file
... ...
examples09/02-iterator/makefile 0 → 100644
  1 +all: foreach
  2 +
  3 +foreach: foreach.cpp
  4 + g++ -g -Wall -pedantic $^ -o $@
  5 +.PHONY: clean
  6 +
  7 +clean:
  8 + -rm foreach
0 9 \ No newline at end of file
... ...
examples09/02-algorithm/algo1.cpp renamed to examples09/03-algorithm/algo1.cpp
examples09/02-algorithm/algo2.cpp renamed to examples09/03-algorithm/algo2.cpp
examples09/02-algorithm/makefile renamed to examples09/03-algorithm/makefile
examples09/03-functionobject/fun1.cpp renamed to examples09/04-functionobject/fun1.cpp
examples09/03-functionobject/fun2.cpp renamed to examples09/04-functionobject/fun2.cpp
examples09/03-functionobject/fun3.cpp renamed to examples09/04-functionobject/fun3.cpp
examples09/03-functionobject/makefile renamed to examples09/04-functionobject/makefile
examples09/04-unordered_set/employee.h renamed to examples09/05-unordered_set/employee.h
examples09/04-unordered_set/makefile renamed to examples09/05-unordered_set/makefile
examples09/04-unordered_set/unordered_set.cpp renamed to examples09/05-unordered_set/unordered_set.cpp
examples09/05-closures/fun1.cpp renamed to examples09/06-closures/fun1.cpp
examples09/05-closures/fun2.cpp renamed to examples09/06-closures/fun2.cpp
examples09/05-closures/fun3.cpp renamed to examples09/06-closures/fun3.cpp
examples09/05-closures/fun4.cpp renamed to examples09/06-closures/fun4.cpp
examples09/05-closures/fun5.cpp renamed to examples09/06-closures/fun5.cpp
examples09/05-closures/makefile renamed to examples09/06-closures/makefile