做相当于合并下面三个函数的工作。
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 << ' '; });***
转载于:https://blog.51cto.com/walkerqt/1276955
本文介绍了一种使用C++模板函数来整合打印字符串向量、整数向量和整数列表的方法,包括使用标准库提供的迭代器和函数特性,以及现代C++11和C++17的lambda表达式来简化代码实现。
2万+

被折叠的 条评论
为什么被折叠?



