c++ list 最后一个元素
时间: 2023-10-18 13:04:17 浏览: 68
要获取 C++ 中 list 的最后一个元素,可以使用 list 的 `back()` 方法。该方法返回 list 中最后一个元素的引用。以下是一个示例代码:
```c++
#include <iostream>
#include <list>
int main() {
std::list<int> myList {1, 2, 3, 4, 5};
int lastElement = myList.back();
std::cout << "The last element is: " << lastElement << std::endl;
return 0;
}
```
输出结果将会是:
```
The last element is: 5
```
相关问题
c++访问list最后一个元素
要访问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删除元素
在C++中,可以使用list容器的erase()方法来删除元素。以下是一个例子:
```c++
#include <iostream>
#include <list>
using namespace std;
int main() {
// 初始化一个int的list
list<int> intList;
for (int i = 0; i <= 3; i++) {
intList.push_back(i);
}
// 使用push_back向List加内容
list<int>::iterator itor; // 声明一个Int的List的迭代器
for (itor = intList.begin(); itor != intList.end(); itor++) {
if (*itor == 2) {
itor = intList.erase(itor); // 删除元素
}
}
// 输出删除后的list
for (itor = intList.begin(); itor != intList.end(); itor++) {
cout << *itor << " ";
}
cout << endl;
return 0;
}
```
上述代码中,我们首先初始化了一个int类型的list,然后使用push_back()方法向list中添加元素。接着,我们使用迭代器遍历list,当遍历到值为2的元素时,使用erase()方法删除该元素。最后,我们再次使用迭代器遍历list,输出删除后的结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)