对于c++的函数模版,可以处理通用的数据类型,特别是stl中针对容器和算法的一些处理,如果自己写某个过程,如果不借助类型推导还真不好处理。
#include <iostream>
#include <string>
#include <vector>
#include <functional>
template <typename T, typename P>
std::vector<T> Filter(const std::vector<T>& vec, P preb){
std::vector<T> res;
for(auto s: vec){
if(preb(s)){
res.push_back(s);
}
}
return res;
}
int main(){
std::string word = "apple";
auto hasWord = [&word](const std::string &s)->bool{ return s.find(word) != std::string::npos; };
std::vector<std::string> words = {"An apple", "orange", "green apple", "grape"};
std::vector<std::string> res = Filter(words, hasWord);
for(auto &s: res){
std::cout<<s<<std::endl;
}
return 0;
}
&nb