I got a question from my professor:
The following is a working program. It prints 41, 42, 43 (each on its own line). Identify and describe the member functions of class List that you can deduce from this code.
1 2 3 4 5 6 7 8 9
int main()
{
List list;
list.insert(41);
list.insert(42);
list.insert(43);
for (int i = 0; i < *list; i++)
cout << list[i] << endl;
}
I want to know how to implement the * operator and [] as the member functions.It should return the size of list and return the element each on each index. Does it follow the overloading operator rules?
The way you access a list is different than an array. Arrays are easy because the memory is contiguous. Lists are not contiguous, so the only way to find, say, the 4th index is to start from the beginning and keep looking until a counter reaches four. Not so bad with 4 items in the list, now try 400. In order to print out every item in the list you would have your program look at nearly 8,000 items. (right? (n/2 * n))
Rather, you need to make an iterator, something that will return a constant pointer to the data in the list:
As STL do not have a class "List" it have class "list".
So, to get this behavior you need to overload operators * and []. Operator * returns counter value of your class. And operator [] an element at position.