Merge the following three functions.
void PrintStringVector(vector<string> vec){ for (auto i : vec) { cout << i << ' '; } cout << endl;}void PrintIntVector(vector<int> vec){ for (auto i : vec) { cout << i << ' '; } cout << endl;}void PrintIntList(list<int> lst){ for (auto i : lst) { cout << i << ' '; } cout << endl;}
Solution 1:
template<typename Container>void PrintContainer(Container container){ for (auto i : container) { cout << i << ' '; } cout << endl;}
Solution 2:
int main(){ list<int> lst = { 1, 3, 5, 4, 9, 6, 3}; copy(lst.cbegin(), lst.cend(), ostream_iterator<int>(cout, " ")); cout << endl; return 0;}
Solution 3: Use boost lambda)
#include <list>#include <iostream>#include <boost/lambda/lambda.hpp>using namespace std;int main(){ list<int> lst = { 1, 3, 5, 4, 9, 6, 3}; for_each (lst.cbegin(), lst.cend(), cout << boost::lambda::_1 << ' '); cout << endl; return 0;}
Solution 4: Use C ++ 11 lambda)
for_each(lst.cbegin(), lst.cend(), [](int i){ cout << i << ' '; });
***
This article is from the "walker" blog, please be sure to keep this source http://walkerqt.blog.51cto.com/1310630/1276955