Ok so i had this code which gave me following output
Elements in List: 2 3 4 5 6 7 8 9 10 11 12
Elements in yourList: -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8
and then i changed the code using the class template so that i could process any datatype and not just int. but now that i changed it it gives me diff output. please tell me what i did wrong
Elements in myList: 4 5 6 7 8 9 10 11 12 0 1098850000
Elements in yourList: 11 12 0 1098850000 134255639 -5 -4 -3 -2 -1 0 1 2 3
Your constructor still doesn't look right, if the calls in main are correct. The two parameters should be the min index and end (as in max index plus one.) Otherwise the loops wouldn't work.
And once you've fixed your constructor, you can move onto operator []
(And please post additional methods with your corrections, otherwise the thread will be rather confusing for people reading it in the future.)
@naraku9333
If you look at the constructor calls, you can see this array is supposed to work with an offset index.
#include <iostream>
usingnamespace std;
template <class T>
class myArray
{
private:
int begin;
int end;
T *array;
public:
myArray(int _begin, int _end)
{
begin = _begin;
end = _end;
array = new T[_end - _begin];
for(int i = 0; i < (_end - _begin); i++)
array[i] = (T)(_begin+i);
}
T& operator [](int index)
{
static T dummy = T();
if((begin <= index) && (index < end))
{
return array[index - begin];
}
return dummy;
}
};
int main()
{
myArray<int> myList(2,13);
myArray<int> yourList(-5,9);
int i;
cout << "Elements in myList: ";
for (i = 2; i < 13; i++)
cout << myList[i] << " ";
cout << endl;
cout << "Elements in yourList: ";
for (i = -5; i < 9; i++)
cout << yourList[i] << " ";
cout << endl;
system("PAUSE");
return 0;
}
It is pretty much the same as sun1520's code was before it was re-broken (e.g. the data members and main() have gone?)
But:
- I followed the C++ standard's libray by having "end" one past the end, so I a using < rather than <= for upperbound
- if a bad index is given to operator[], I do not return the first element. Instead I return a static, zero-ed element
- and I think that as far as names go, begin and end are clearer than place and _size.
The results are:
Elements in myList: 2 3 4 5 6 7 8 9 10 11 12
Elements in yourList: -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8
Press any key to continue . . .