本文共 1185 字,大约阅读时间需要 3 分钟。
做相当于合并下面三个函数的工作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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; } |
方案一:
1 2 3 4 5 6 7 8 9 | template < typename Container> void PrintContainer(Container container) { for ( auto i : container) { cout << i << ' ' ; } cout << endl; } |
方案二:
1 2 3 4 5 6 7 | 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)
1 2 3 4 5 6 7 8 9 10 11 | #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)
1 | for_each(lst.cbegin(), lst.cend(), []( int i){ cout << i << ' ' ; }); |
***
本文转自walker snapshot博客51CTO博客,原文链接http://blog.51cto.com/walkerqt/1276955如需转载请自行联系原作者
RQSLT