jeudi 28 janvier 2016

C++ standard library forward_list issue

I need some help solving the exercise 9.28 from the C++ Primer 5th edition. Here is the task:

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.

I can't get the idea written in the book as to how forward_list actually works and why we indeed need it, so I'm asking for help. Below is the code I wrote which is incomplete and I need someone help me finish it:

#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;
}

Any suggestion to refactor the code is welcome!

Aucun commentaire:

Enregistrer un commentaire