c++11 - C++ standard library forward_list issue -
i need solving exercise 9.28 c++ primer 5th edition. here task:
write function takes forward_list , 2 additional string arguments. function should find first string , insert second following first. if first string not found, insert second string @ end of list.
i can't idea written in book how forward_list
works , why indeed need it, i'm asking help. below code wrote incomplete , need 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; // put here?! break; } // put here?!... ++curr; } (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 refactor code welcome!
you can write function following way using member function 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" ); ( const std::string &s : lst ) std::cout << s << ' '; std::cout << std::endl; find_and_insert( lst, "zero", "two"); ( const std::string &s : lst ) std::cout << s << ' '; std::cout << std::endl; find_and_insert( lst, "zero", "one"); ( const std::string &s : lst ) std::cout << s << ' '; std::cout << std::endl; find_and_insert( lst, "two", "three"); ( const std::string &s : lst ) std::cout << s << ' '; std::cout << std::endl; find_and_insert( lst, "four", "four"); ( const std::string &s : lst ) std::cout << s << ' '; std::cout << std::endl; }
the program output is
zero 0 2 0 1 2 0 1 2 3 0 1 2 3 4
Comments
Post a Comment