A "Try this" in Chapter 20 has the following specs:
Write a function void copy(int* f1, int* e1, int* f2) that copies the elements
of an array of int s defined by [ f1 : e1 ) into another [ f2 : f2+(e1–f1) ). Use only
the iterator operations mentioned above (not subscripting).
The iterator operations mentioned above that are of course these ones:
p==q, p != q, *p, *p==val, val==*p, ++p
.
I'm having a hard time with this, though. Here's my code:
// Osman Zakir
// 11 / 8 / 2017
// Bjarne Stroustrup: Programming: Principles and Practice Using C++ 2nd Edition
// Chapter 20 Try This:
// Program to define a function void copy(int* f1, int* e1, int* f2) which copies the contents of one array into another.
#include "../../cust_std_lib_facilities.h"
#include <iostream>
void copy(int *f1, int *e1, int *f2);
int main()
{
int *arr1 = newint[10];
for (int i = 0; i < 10; ++i)
{
*(arr1 + i) = i + 1;
}
for (int i = 0; i < 10; ++i)
{
std::cout << *(arr1 + i) << '\n';
}
int *arr2 = newint[10];
copy(arr1, arr1 + 10, arr2);
for (int i = 0; i < 10; ++i)
{
std::cout << *(arr2 + i) << '\n';
}
delete[] arr1;
delete[] arr2;
keep_window_open();
}
void copy(int *f1, int *e1, int *f2)
{
for (int i = *f1; i != (*f2 + (*e1 - *f1)); ++i)
{
*(f2 + i) = *(f1 + i);
if (i >= 10)
{
break;
}
}
}
The very fact that it seems like the array being copied into is bigger than the one being copied is already a problem for me. I don't understand how to make this work without making the index for the original array (the one being copied) go out of bounds. If I change the for loop to this (and if this is more how it should be):
The second loop is closer to how it should be done, but you need to use two iterators, one for each array. Then you can use the dereference operator (*) to access the array elements that the iterators refer to which is necessary when doing the copying of values from one array to the other.
i is used to iterate the [ f1 : e1 ) range so to check if the end has been reached you should use i != e1. If you really want to check against (f2 + (e1 - f1)) you should instead use the j iterator, j != (f2 + (e1 - f1)).