c++ list erase函数
erase的作用是,使作为参数的迭代器失效,并返回指向该迭代器下一参数的迭代器。
删除的是list.begin()~--(--list.end())之间的元素
一个例子:
#include <iostream>
#include <list>
using namespace std;
list<int> A;
list<int> B;
void show(list<int> A)
{
for (list<int>::iterator it = A.begin(); it != A.end(); it++)
cout << *it << " ";
cout << endl;
}
int main()
{
list<int>::iterator it;
A.push_back(1);
A.push_back(2);
A.push_back(3);
A.push_back(4);
cout << "初始化前" << endl;
show(A);
it = A.begin();
cout << *it << endl; // 1
it = A.erase(it); // 删除1
cout << *it << endl; // 2
show(A);
return 0;
}
这里很显然是符号前面所说的erase的返回值的,返回删除位置迭代器的下一个迭代器。
删除的是--list.end()位置处的元素
但是如果删除的迭代器指向列表的最后一个元素呢(即it=--list.end()
),如果还是之前的规律的话,那么erase应该返回的是list.end()
,但是事实上并非如此,此时返回的是删除位置迭代器的上一个迭代器。
一个例子:
#include <iostream>
#include <list>
using namespace std;
list<int> A;
list<int> B;
void show(list<int> A)
{
for (list<int>::iterator it = A.begin(); it != A.end(); it++)
cout << *it << " ";
cout << endl;
}
int main()
{
list<int>::iterator it;
A.push_back(1);
A.push_back(2);
A.push_back(3);
A.push_back(4);
cout << "初始化前" << endl;
show(A);
it = --A.end();
cout << *it << endl; // 4
it = A.erase(it); // 删除4
cout << *it << endl; // 3
show(A);
return 0;
}
删除list.end()
别想了,直接报错,程序跑不完整
本文作者:请去看诡秘之主
本文链接:https://www.cnblogs.com/xjy881/p/16930102.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步