forward_list删除元素

文章展示了如何使用C++标准库中的forward_list容器,删除列表中的奇数元素以及在特定字符串出现的位置插入新的字符串。通过迭代器管理和erase_after函数实现元素删除,利用insert_after进行元素插入。
摘要由CSDN通过智能技术生成

1.删除forward_list中的奇数元素

#include <iostream>
#include <list>
#include <vector>
#include <string>
#include <deque>
#include <forward_list>

#define element_num(arr) (sizeof arr / sizeof(arr[0]))

int main()
{
    std::forward_list<int> fst{1, 2, 3, 4, 5, 6};
    auto before_process = fst.before_begin();
    auto process = fst.begin();
    while (process != fst.end()){
        if (*process % 2)
            process = fst.erase_after(before_process);
        else{
            before_process = process;
            ++process;
        }
    }
    //奇数删除元素时,首前迭代器位置不发生变化
    for (const auto &i : fst)
        std::cout << i << " ";

    return 0;
}

重点:在while循环中利用erase_after的返回值更新当前元素迭代器。

2.

#include <forward_list>
#include <string>
#include <iostream>

void str_in(std::forward_list<std::string> &fst, const std::string &s1, const std::string &s2){
    auto it_now = fst.begin();
    auto it_before = fst.before_begin();
    int counter = 0;
    while (it_now != fst.end()){
        if (*it_now == s1){
            it_before = fst.insert_after(it_now, s2);
            it_now = ++it_before;
            ++counter;
        }
        else
            it_before = it_now++;
    }
    if (counter == 0)
        fst.insert_after(it_before, s2);
}

int main()
{
    std::string str1 = "Hello world!";
    std::string str2 = "Ni Hao!";
    std::forward_list<std::string> lst{"abc", str1, "def", "hij"};
    str_in(lst, str1, str2);

    for (const auto &i : lst)
        std::cout << i << std::endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值