C++ 标准库 forward_list 问题

C++ standard library forward_list issue

我需要一些帮助来解决 C++ Primer 第 5 版中的练习 9.28。这是任务:

Write a function that takes a forward_list and two additional string arguments. The function should find the first string and insert the second immediately following the first. If the first string is not found, then insert the second string at the end of the list.

我无法理解书中关于 forward_list 实际如何工作以及我们确实需要它的原因,所以我寻求帮助。下面是我写的不完整的代码,我需要有人帮我完成它:

#include <iostream>
#include <forward_list>

using namespace std;

void find_and_insert(forward_list<string>& flstr, const string& needle, const string& rplc) {

    auto curr = flstr.begin();
    auto last = flstr.end();
    bool found = false;

    while (curr != last) {

        if (*curr == needle) {

            found = true;
            // what to put here?!
            break;
        }

        // what to put here?!... 
        ++curr;
    }

    for (const auto& elem : flstr) {

        cout << elem << endl;
    }

    return;
}

int main(int argc, char *argv[]) {

    cout << endl;

    forward_list<string> flstring = {"Foo", "Bar", "Baz", "Tomcat"};

    find_and_insert(flstring, "Bar", "Insertion");

    cout << endl;

    return EXIT_SUCCESS;
}

欢迎任何重构代码的建议!

对于第一部分,您需要使用 insert_after。您会将当前迭代器和要插入的字符串传递给它,它会在当前元素之后插入该字符串。

至于在末尾插入一个元素变得有点复杂,因为 std::forward_list::iterator 是一个 ForwardIterator. Luckily we have the before_begin 它将 return 一个迭代器 1 在开始之前。您可以捕获该迭代器,并且每次递增 curr 时您也会递增该迭代器。一旦循环结束,检查 found 是否为 true。如果是,那么您可以在开始迭代器之前使用 1,因为它现在指向最后一个元素。就像在 while 循环中一样,您将使用字符串将其传递给 insert_after

您可以使用成员函数按以下方式编写函数before_begin

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

void find_and_insert( std::forward_list<std::string> &lst, 
                      const std::string &src, 
                      const std::string &dest ) 
{
    auto before = lst.before_begin();
    auto first  = lst.begin();

    while ( first != lst.end() && *first != src ) ++before, ++first;

    lst.insert_after( first == lst.end() ? before : first, dest );
}

int main()
{
    std::forward_list<std::string> lst;

    find_and_insert( lst, "one", "zero" );

    for ( const std::string &s : lst ) std::cout << s << ' ';
    std::cout << std::endl;

    find_and_insert( lst, "zero", "two");

    for ( const std::string &s : lst ) std::cout << s << ' ';
    std::cout << std::endl;

    find_and_insert( lst, "zero", "one");

    for ( const std::string &s : lst ) std::cout << s << ' ';
    std::cout << std::endl;

    find_and_insert( lst, "two", "three");

    for ( const std::string &s : lst ) std::cout << s << ' ';
    std::cout << std::endl;

    find_and_insert( lst, "four", "four");

    for ( const std::string &s : lst ) std::cout << s << ' ';
    std::cout << std::endl;
}    

程序输出为

zero 
zero two 
zero one two 
zero one two three 
zero one two three four