原函数
vectorsub_vec(const vector &vec, int val) { vector local_vec(vec); sort(local_vec.begin(), local_vec.end()); vector ::iterator iter = find_if(local_vec.begin(), local_vec.end(), bind2nd(greater (), val)); local_vec.erase(iter, local_vec.end()); return local_vec; }
改动后模板函数:
templateOutputIterator sub_(InputIterator first, InputIterator last, OutputIterator at, const ElemType &val, Comp pred) { OutputIterator at_begin = at; while (first != last) *at++ = *first++; OutputIterator at_end = at; sort(at_begin, at_end); OutputIterator iter = find_if(at_begin, at_end, bind2nd(pred, val)); return iter; }
使用中对于给定待过滤数据,最终返回输出迭代器的终止位置
int main()
{
const int elem_size = 8;
int ia[elem_size] = {12, 8, 43, 0, 6, 21, 3, 7};
vector ivec(ia, ia + elem_size);
int ia2[elem_size];
vector ivec2(elem_size);
cout << "normal function:" << endl;
vector x = sub_vec(ivec, 8);
for (auto i : x)
cout << i << ' ';
cout << endl;
cout << "template function vector : " << endl;
vector::iterator iter = sub_(ivec.begin(), ivec.end(),
ivec2.begin(), elem_size,
greater());
for (auto it = ivec2.begin(); it != iter; ++it)
cout << *it << ' ';
cout << endl;
cout << "template function array : " << endl;
int *iit = sub_(ia, ia + elem_size,
ia2, elem_size, greater());
for (int ix = 0; ia2 + ix != iit; ++ix)
cout << *(ia2 + ix) << ' ';
cout << endl;
return 0;
}
最终输出结果为:
normal function: 0 3 6 7 8 template function vector : 0 3 6 7 8 template function array : 0 3 6 7 8



