c++ std list 遍历循环中删除成员

不可以直接删除,会导致迭代器失效,然后引发段错误,
应该先把要删除的成员备份,然后把迭代器++,然后再删除备份的成员,代码示例如下:

#include <list>
#include <algorithm>
#include <iostream>

using namespace std;

void printlist(const list<int> l)
{

        for(auto it=l.begin();it!=l.end();it++)
        {
                cout<<*it<<" ";
        }
        cout<<endl;
}


int main()
{
        list<int> ll;
        for(int i=0;i<10;i++)
        {
                ll.push_front(i);
        }

cout<<"ori:"<<endl;
        printlist(ll);

        for(auto it=ll.begin();it!=ll.end();it++)
        {
                if(*it%2==0)
                {
                        auto bak=it;
                        it++;
                        ll.erase(bak);
                }
        }
cout<<"after del:"<<endl;
        printlist(ll);
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++,`std::list`是一种双链表数据结构,它允许高效地插入、删除元素,并且从头部和尾部访问元素速度很快。为了循环遍历`std::list`,可以使用迭代器(iterator),这使得遍历非常简单。 ### 使用标准库迭代器遍历 通常我们会创建一个`std::list<T>`容器,然后通过迭代器遍历的每个元素。下面是一个具体的例子: ```cpp #include <iostream> #include <list> using namespace std; int main() { // 初始化列表 list<int> my_list = {10, 20, 30, 40, 50}; // 使用反向迭代器从末尾开始遍历 for (auto it = my_list.rbegin(); it != my_list.rend(); ++it) { cout << *it << " "; // 输出每个元素 } return 0; } ``` 在这个例子,我们首先包含了必要的头文件并声明了一个包含整数的`std::list`容器。然后我们使用反向迭代器(`rbegin()` 和 `rend()` 函数分别获取列表的第一个和最后一个元素的位置)从末尾开始遍历整个列表,并打印出每个元素的值。 ### 自定义迭代器遍历 除了使用标准库提供的迭代器外,也可以自定义迭代器来遍历`std::list`。但是这种方法相对复杂,因为需要实现迭代器的基本操作(如`operator*`用于访问当前元素,`operator->`对于指针迭代器),以及迭代器的移动操作(例如,将迭代器向前或向后移动)。以下是自定义迭代器的一个简化的示例: ```cpp class MyListIterator { public: int value; bool is_end; MyListIterator(int v, bool end) : value(v), is_end(end) {} // 重载运算符* operator int() const { return value; } // 检查是否到达了列表结尾 bool operator==(const MyListIterator& other) const { return is_end == other.is_end; } bool operator!=(const MyListIterator& other) const { return !(*this == other); } }; // 实现一个函数来遍历自定义迭代器 void traverse_custom_iterator(const std::list<int>& list) { auto iter = list.begin(); while(iter != list.end()) { cout << *iter << " "; ++iter; } } int main() { std::list<int> my_list = {10, 20, 30, 40, 50}; traverse_custom_iterator(my_list); return 0; } ``` 在这段代码,我们定义了一个名为`MyListIterator`的类,实现了基本的迭代器操作。然后我们在主函数创建了一个`std::list`实例,并使用这个自定义迭代器来遍历列表。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值