Skip to content

Instantly share code, notes, and snippets.

@Mooophy
Last active August 29, 2015 14:07
Show Gist options
  • Save Mooophy/adfb7e92565e9e23e311 to your computer and use it in GitHub Desktop.
Save Mooophy/adfb7e92565e9e23e311 to your computer and use it in GitHub Desktop.
C++ Primer 5th exercise 9.45 generics version
//! @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.
@Mooophy
Copy link
Author

Mooophy commented Oct 5, 2014

@pezy
Copy link

pezy commented Oct 7, 2014

so beautiful! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment