Screenplay: Pointer Arithmetic, And Algorithms

#include <iostream>
using namespace std;

int main()
{
    int a[3] = {100, 200, 300};

    int *a_begin = a;
    int *a_end = a + 3;

    int *run = a_begin;
    while (run != a_end)
        cout << *run++ << endl;       // <--- explicit precedence: *(run++)

    return 0;
}
  • Transform to sum

#include <iostream>
using namespace std;

int main()
{
    int a[3] = {100, 200, 300};

    int *a_begin = a;
    int *a_end = a + 3;

    int *run = a_begin;
    int sum = 0;
    while (run != a_end)
        sum += *run++;

    cout << sum << endl;

    return 0;
}
  • Transform to sum() function

#include <iostream>
using namespace std;

int sum(int *begin, int *end)        // <--- pass in *range delimiters* [begin, end)
{
    int sum = 0;
    while (begin != end)
        sum += *begin++;
    return sum;
}

int main()
{
    int a[3] = {100, 200, 300};
    cout << sum(a, a+3) << endl;
    return 0;
}
  • Transform to copy()

#include <iostream>
using namespace std;

void copy(int *src_begin, int *src_end, int *dst_begin)
{
    while (src_begin != src_end)
        *dst_begin++ = *src_begin++;
}

int main()
{
    int a[3] = {100, 200, 300};
    int dst[3];
    copy(a, a+3, dst);

    for (int *run=dst; run!=dst+3; run++)       // <--- clumsy old C loop
        cout << *run << endl;
    return 0;
}
#include <iostream>
using namespace std;

void copy(int *src_begin, int *src_end, int *dst_begin)
{
    while (src_begin != src_end)
        *dst_begin++ = *src_begin++;
}

int main()
{
    int a[3] = {100, 200, 300};
    int dst[3];
    copy(a, a+3, dst);

    for (int i: dst)                  // <--- "range based for" from C++11
        cout << i << endl;
    return 0;
}