c++ list 最后一个元素
时间: 2023-09-25 13:13:07 浏览: 179
要获取 C++ 中 std::list 的最后一个元素,可以使用 `back()` 函数。该函数返回一个引用,指向列表中的最后一个元素。以下是一个简单的示例代码:
```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 in the list is: " << lastElement << std::endl;
return 0;
}
```
输出:
```
The last element in the list 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,输出删除后的结果。