c++访问list最后一个元素
时间: 2023-10-30 16:05:11 浏览: 67
要访问list的最后一个元素,可以使用list的成员函数`back()`,它返回list的最后一个元素。以下是一个示例:
```c++
#include <iostream>
#include <list>
int main() {
std::list<int> mylist = {1, 2, 3, 4, 5};
std::cout << "Last element of mylist is: " << mylist.back() << std::endl;
return 0;
}
```
输出:
```
Last element of mylist is: 5
```
相关问题
c++访问list第一个元素
要访问list的第一个元素,可以使用list的成员函数front(),该函数返回list中第一个元素的引用。例如:
```c++
#include <iostream>
#include <list>
int main() {
std::list<int> mylist = {1, 2, 3};
int first = mylist.front();
std::cout << "The first element is: " << first << std::endl;
return 0;
}
```
输出:
```
The first element is: 1
```
c++中list通过下标访问元素
在C++中,标准库中的`std::list`是一个双向链表,不能像数组一样通过下标访问元素。这是因为链表元素的访问是非连续的,需要依次遍历链表才能找到对应的元素。
如果你需要按下标访问元素,可以考虑使用`std::vector`或者`std::array`等容器。如果你需要使用链表,可以使用迭代器来遍历链表中的元素。例如:
```c++
#include <iostream>
#include <list>
int main() {
std::list<int> mylist = {1, 2, 3, 4, 5};
// 使用迭代器遍历链表
int i = 0;
for (auto it = mylist.begin(); it != mylist.end(); ++it) {
if (i == 2) {
std::cout << *it << std::endl; // 输出第三个元素
break;
}
++i;
}
return 0;
}
```
以上代码输出结果为:
```
3
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)