c++list求大小
时间: 2023-08-15 20:06:19 浏览: 53
如果你是使用标准库中的`std::list`,那么可以使用`size()`成员函数来获取列表中元素的数量,例如:
```c++
#include <iostream>
#include <list>
int main() {
std::list<int> my_list = {1, 2, 3, 4, 5};
std::cout << "The size of my_list is: " << my_list.size() << std::endl; // 输出:The size of my_list is: 5
return 0;
}
```
如果你使用的是自定义的链表实现,你需要在链表类中添加一个成员函数来返回链表的大小,例如:
```c++
#include <iostream>
class MyList {
public:
// ... 其他成员函数
int size() const {
int count = 0;
Node* current = head_;
while (current != nullptr) {
count++;
current = current->next;
}
return count;
}
private:
// ... 其他成员变量和函数
};
```
在这个例子中,链表类`MyList`添加了一个名为`size()`的成员函数来计算链表中节点的数量。该函数遍历链表并计数,直到最后一个节点。