C++ 有人能解释一下这个C++;给我的代码是LinkedList程序的一部分吗?
我知道这个问题不会很具体,但我不知道这段代码在做什么: 我有一个类的构造函数:C++ 有人能解释一下这个C++;给我的代码是LinkedList程序的一部分吗?,c++,C++,我知道这个问题不会很具体,但我不知道这段代码在做什么: 我有一个类的构造函数: ListNode(const T&data):数据(data),next(nullptr){}将next初始化为nullptr 那么我有这个代码: template <typename T> const T & List<T>::operator[](unsigned index) { ListNode *thru = head_; while (index > 0 &
ListNode(const T&data):数据(data),next(nullptr){}
将next初始化为nullptr
那么我有这个代码:
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;
}
模板
常量T和列表::运算符[](无符号索引){
ListNode*thru=头部;
while(索引>0&&thru->next!=nullptr){
通过=通过->下一步;
索引--;
}
通过->数据返回;
}
这是否试图将
[]
定义为在给定“索引”处返回“数据”的运算符?什么是thru=thru->next代码>尝试完成?有人能帮忙吗?还有,为什么要在此代码上下文中执行索引--
这是否试图将[]定义为在给定“索引”处返回“数据”的运算符
对。基本上,这意味着你可以做到:
List<int> l; //suppose it has values
int x = l[3]; //access the third element.
如果索引为3,它将递减3次,至
将在列表中向前移动3项。换句话说,我们在列表中向前移动,直到索引不是0。当索引达到0时,thru
包含位置index
处的值,该值从函数返回。thru=thru->next代码>正在设置指向列表中下一个元素的指针。这是通常遍历链接列表的方式此函数在链接列表中迭代(while循环)并返回传递给它的链表的索引/节点处的数据。它如何知道何时到达我们指定的“索引”?通过组合index>0
和index--
-索引在频繁迭代时将变为0enough@UnholySheep哦,哇,明白了。难道没有更好的方法来创建这个循环吗?
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
}