Last active
August 29, 2015 14:07
-
-
Save Mooophy/adfb7e92565e9e23e311 to your computer and use it in GitHub Desktop.
C++ Primer 5th exercise 9.45 generics version
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//! @author @Queequeg @Alan | |
//! @date 4 Oct,2014. | |
//! | |
//! Exercise 9.45: | |
//! Write a funtion that takes a string representing a name and two other | |
//! strings representing a prefix, such as “Mr.” or “Ms.” and a suffix, | |
//! such as “Jr.” or “III”. Using iterators and the insert and append functions, | |
//! generate and return a new string with the suffix and prefix added to the | |
//! given name. | |
//! | |
#include<iterator> | |
using std::back_inserter; | |
#include<utility> | |
using std::move; | |
#include<algorithm> | |
using std::copy; | |
#include <iostream> | |
using std::cout; using std::endl; | |
#include <string> | |
using std::string; | |
//! included files added by alan | |
#include <list> | |
#include <deque> | |
template<typename C> | |
inline typename C::iterator | |
pre_suffix(C &s, | |
typename C::iterator p_beg, typename C::iterator p_end, | |
typename C::iterator s_beg, typename C::iterator s_end) | |
{ | |
C c{move(s)}; | |
s.clear(); | |
move(p_beg, p_end, back_inserter(s)); | |
s.push_back(' '); | |
move(c.begin(), c.end(), back_inserter(s)); | |
s.push_back(' '); | |
move(s_beg, s_end, back_inserter(s)); | |
return s.begin(); | |
} | |
int main() | |
{ | |
//! container = string | |
string s("alan"), pre("Mr."), su("Jr."); | |
pre_suffix(s, pre.begin(), pre.end(), su.begin(), su.end()); | |
cout << s << endl; | |
//! container = vector | |
std::vector<char> vs{'a','l','a','n'}, vpre{'M','r','.'}, vsu{'J','r','.'}; | |
pre_suffix(vs, vpre.begin(), vpre.end(), vsu.begin(), vsu.end()); | |
for(auto c : vs) | |
cout << c; | |
cout << endl; | |
//! container = list | |
std::list<char> ls{'a','l','a','n'}, lpre{'M','r','.'}, lsu{'J','r','.'}; | |
pre_suffix(ls, lpre.begin(), lpre.end(), lsu.begin(), lsu.end()); | |
for(auto c : ls) | |
cout << c; | |
cout << endl; | |
//! container = deque | |
std::deque<char> ds{'a','l','a','n'}, dpre{'M','r','.'}, dsu{'J','r','.'}; | |
pre_suffix(ds, dpre.begin(), dpre.end(), dsu.begin(), dsu.end()); | |
for(auto c : ds) | |
cout << c; | |
cout << endl; | |
return 0; | |
} | |
//! @output : | |
//Mr. alan Jr. | |
//Mr. alan Jr. | |
//Mr. alan Jr. | |
//Mr. alan Jr. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
so beautiful! 👍