如何在C++ STL中从List中删除最后一个元素
给定一个List,任务是在C++中从此List中删除最后一个元素。
例子:
输入:list = [10 20 30 70 80 90 100 40 50 60]
输出:10 20 30 40 50 60 70 80 90
输入:list = [1 2 3 4 5]
输出:1 2 3 4
C++
List是一种关联容器,其中每个元素必须是唯一的,因为元素的值识别它。一旦将元素添加到列表中,就无法修改元素的值,尽管可以删除和添加该元素的修改值。
可以通过将其迭代器传递到erase函数来删除List的最后一个元素。
语法:
iterator erase(const_iterator positionOfElementToBeDeleted);
C++
方法: 可以通过将其迭代器传递到erase函数来轻松删除最后一个元素。要到达指向最后一个元素的迭代器,有两种方法:
- Method 1:
cpp prev(listInt.end())
下面是上述方法的实现:
程序 1:
// C++ program to delete last element
// of a List by passing its iterator
# include <iostream>
# include <list>
using namespace std;
// Function to print the list
void printList(list<int> mylist)
{
// Get the iterator
list<int>::iterator it;
// printing all the elements of the list
for (it = mylist.begin(); it != mylist.end(); ++it)
cout << ' ' << *it;
cout << '\n';
}
// Function to delete last element of list
// using method 1
void deleteByMethod1(list<int> mylist)
{
// printing all the elements of the list
cout << "\n原始列表:";
printList(mylist);
// Get the iterator
list<int>::iterator it;
// Get the positionOfElementToBeDeleted
// using method 1
it = prev(mylist.end());
// Erase the last element
// currently pointed by the iterator
mylist.erase(it);
// printing all the elements of the list
cout << "删除后列表:";
printList(mylist);
}
// Driver code
int main()
{
list<int> mylist;
// Get the list
for (int i = 1; i < 10; i++)
mylist.push_back(i * 10);
// Method 1 to get positionOfElementToBeDeleted
deleteByMethod1(mylist);
return 0;
}
C++
输出:
原始列表: 10 20 30 40 50 60 70 80 90
删除后列表: 10 20 30 40 50 60 70 80
C++
- 方法 2:
list::iterator it = listInt.end();
--it;
C++
下面是上述方法的实现:
程序 2:
// C++ program to delete last element
// of a List by passing its iterator
# include <iostream>
# include <list>
using namespace std;
// Function to print the list
void printList(list<int> mylist)
{
// Get the iterator
list<int>::iterator it;
// printing all the elements of the list
for (it = mylist.begin(); it != mylist.end(); ++it)
cout << ' ' << *it;
cout << '\n';
}
// Function to delete last element of list
// using method 2
void deleteByMethod2(list<int> mylist)
{
// printing all the elements of the list
cout << "\n原始列表:";
printList(mylist);
// Get the iterator
list<int>::iterator it;
// Get the positionOfElementToBeDeleted
// using method 2
it = --mylist.end();
// Erase the last element
// currently pointed by the iterator
mylist.erase(it);
// printing all the elements of the list
cout << "删除后列表:";
printList(mylist);
}
// Driver code
int main()
{
list<int> mylist;
// Get the list
for (int i = 1; i < 10; i++)
mylist.push_back(i * 10);
// Method 2 to get positionOfElementToBeDeleted
deleteByMethod2(mylist);
return 0;
}
C++
输出:
原始列表: 10 20 30 40 50 60 70 80 90
删除后列表: 10 20 30 40 50 60 70 80
C++