Hi, I am altering a vector class to take in custom index ranges, like [-5, 5] and [10, 20]. My teacher wants us to have a "myZero" variable that points to where the 0th element is or would be. But if I do this
customvector <int> example(1, 5);
where the parameters are the index boundaries, how can I have a pointer pointing to the 0th element if the space was not allocated? I am just conceptually lost on how to do this. Thanks.
You're probably supposed to have it point to the first element of the allocated array.
Hard to say without seeing the full task description.
It's possible to do arbitary pointer arithmetic, e.g.: int* myZero=newint[5]-1;
While this compiles, it's undefined behavior and therefore incorrect, so I hope that's not what your teacher was expecting.
Ah. Yes, you can reach that by pointer arithmetic: int* myZero=myList-myLower;
However, doing that is not safe - it's okay to have a pointer exactly one element past the end of an array (so to -4 in this case), but everything beyond that is not allowed.
constint myLower = -10, myUpper = -5;
constint size = 1 + myUpper - myLower;
int* myList = newint[size];
// so that the elements myList[0] through myList[myUpper - myLower] are valid
int* myZero = myList - myLower;
Now we have:
(myZero + myLower) == (myList + 0) is true.
and
(myZero + myUpper) = (myList + myUpper - myLower) = (myList + size - 1) = OK
I think the point is this: Although myZero points to a location in memory which has not been allocated for our use, this memory location is still a valid point to calculate an offset from.
If we do not refer to elements outside the range of
myZero[myLower] through myZero[myUpper]
same as we would not refer to elements outside the range of
myList[0] through myList[size-1]
Ok, I see that myZero will be myList - myLower. How can I use myZero when overloading the [] operator? My teacher says we can't just calculate the myZero index to the myList index using an integer everytime we use the subscript operator and that we have to use myZero.
Item & operator [] (int index)// pass index in range myLower <= index <= myUpper
{
checkIndex(index);// constrain index to the range myLower <= index <= myUpper
return myZero[index];
}
That code helped me understand more than my teacher...Thank you so much! I was just confused as to how myZero and myList compared to each other but I get it now. Thanks again