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;
}

image
这里很显然是符号前面所说的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;
}

image

删除list.end()

别想了,直接报错,程序跑不完整

posted @ 2022-11-27 17:06  请去看诡秘之主  阅读(970)  评论(0编辑  收藏  举报