Reputation: 69
I know this question won't be specific but I can't figure out what this code is doing:
I have a constructor for a class:
ListNode(const T & data) : data(data), next(nullptr) {}
that initializes next as a nullptr.
Then I have this code:
template <typename T>
const T & List<T>::operator[](unsigned index) {
ListNode *thru = head_;
while (index > 0 && thru->next != nullptr) {
thru = thru->next;
index--;
}
return thru->data;
}
Is this trying to define []
as an operator that will return the 'data' at the given 'index'? And what is thru = thru->next;
trying to accomplish? Can someone help? Also what why index--
is being done in the context of this code?
Upvotes: 1
Views: 80
Reputation: 9331
Is this trying to define [] as an operator that will return the 'data' at the given 'index'?
Yes. Basically it means you can do this:
List<int> l; //suppose it has values
int x = l[3]; //access the third element.
And what is thru = thru->next; trying to accomplish?
It is trying to find the index
position provided in the argument. You see, lists can't be accessed directly with indexes. Let me explain with values:
suppose index = 3
// loop keeps running till index is not 0
while (index > 0 && thru->next != nullptr) {
thru = thru->next; //move forward in list, "next" is the next item in list
index--; //decrease index by 1 on every iteration
}
If the index is 3, it will be decremented 3 times, and thru
will move forward in list by 3 items. In other words, we move forward in list till index is not 0. When index has reached 0, thru
contains the value at position index
and that value is returned from the function.
Upvotes: 2