统计一个vector中奇偶数的个数:
lambda做法:这样就避免了再多定义统计函数,简洁了不少
template<typename U> //要使用模板,因为返回值可能会多样
int Counter(vector<int>& numberVec, U filter) {
int count = 0;
for (auto& x : numberVec) {
if (filter(x) == 1) {
count++;
}
}
return count;
}
//过滤函数的使用 奇数
//统计函数
int CountOdds(vector<int>& numberVec) {
return Counter(numberVec, [](int x) {return x % 2 != 0; });
}
int CountEvens(vector<int>& numberVec) {
return Counter(numberVec, [](int x) {return x % 2 == 0; });
}
统计vector中大于某个数的数的个数:
template<typename U>
int GreatCounter(vector<int>& numberVec, U filter) {
int count = 0;
for (auto& x : numberVec) {
if (filter(x) == 1) {
count++;
}
}
return count;
}
int counterGreater(vector<int>& numberVec, int y) {
return GreatCounter(numberVec, [=](int x) {return x > y; }); //返回的是bool类型
}
把A中的数值倒序排序后复制到B中
template<typename U> //遍历处理函数
void travers(vector<int>& numberVec, U process) {
for (auto& x : numberVec) {
process(x);
}
}
void theCopyFunction(vector<int>& a,vector<int>& b, int y) {
travers(a, [&, y](int x) {
if (x > y) {
b.push_back(x);
}
}
);
}