做相當於合並下面三個函數的工作。
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;
}方案一:
template<typename Container>
void PrintContainer(Container container)
{
for (auto i : container)
{
cout << i << ' ';
}
cout << endl;
}方案二:
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;
}方案三:用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;
}方案四:用C++11的lambda)
for_each(lst.cbegin(), lst.cend(), [](int i){ cout << i << ' '; });***
本文出自 “walker” 博客,請務必保留此出處http://walkerqt.blog.51cto.com/1310630/1276955