c++ 列表删除元素(erase)

本文详细介绍了如何使用C++标准模板库中的list容器进行各种操作,包括元素的遍历、删除首元素、删除指定范围内的元素以及使用C++11及以后版本的功能来删除所有偶数元素。通过具体的代码示例,读者可以了解到list容器的基本用法及其高级功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

#include <list>
#include <iostream>
#include <iterator>
using namespace std;
int main( )
{
    list<int> c{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    for (auto &i : c) {
        cout << i << " ";
    }
    cout << '\n';
    c.erase(c.begin());//删除第一个元素
    for (auto &i : c) {
        cout << i << " ";
    }
    cout << '\n';
    list<int>::iterator range_begin = c.begin();
    list<int>::iterator range_end = c.begin();
    advance(range_begin,2);
    advance(range_end,5);
    c.erase(range_begin, range_end);
    for (auto &i : c) {
        cout << i << " ";
    }
    cout << '\n';
    // Erase all even numbers (C++11 and later)
    for (auto it = c.begin(); it != c.end(); ) {
        if (*it % 2 == 0) {
            it = c.erase(it);//删除偶数
        } else {
            ++it;
        }
    }
    for (auto &i : c) {
        cout << i << " ";
    }
    cout << '\n';
}

 

转载于:https://www.cnblogs.com/sea-stream/p/10110904.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值