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.
![](https://i-blog.csdnimg.cn/blog_migrate/6c1c7a3ca612f803ba4fe5ffdefe927b.png)
#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;
}