我要实现一个template function ,编译通过,运行的时候出现“Debug Assertion Failed” 错误???
rt
代码:
#include <algorithm>//泛型算法#include <iostream>#include <vector>#include <functional>//函数模板using namespace std;template <typename InputIterator,typename ElemType,typename Comp,typename Input>Inputsub_vec(InputIterator first,InputIterator last,Input at, const ElemType &val,Comp pred){ sort(first,last); first=find_if(first,last,bind2nd(pred,val)); at.erase(first,last); return at;}int main(){ int ia[6]={12,2,4,32,7,1}; vector<int>ivec(ia,ia+6); ivec=sub_vec(ivec.begin(),ivec.end(),ivec,6,greater<int>()); for(int ix=0;ix<ivec.size();ix++) cout << ivec[ix] << " "; cout << endl; return 0;}template <typename InputIterator,typename ElemType,typename Comp,typename Input>Inputsub_vec(InputIterator first,InputIterator last,Input at, const ElemType &val,Comp pred){ sort(first,last); if (last != at.end() && first != at.begin()) cout<<"first and last have changed!\n"; //first=find_if(first,last,bind2nd(pred,val)); first=find_if(at.begin(),at.end(),bind2nd(pred,val)); //at.erase(first,last); at.erase(first,at.end()); return at;}
[解决办法]
#include <algorithm>//泛型算法
#include <iostream>
#include <vector>
#include <functional>//函数模板
using namespace std;
template <typename InputIterator,typename ElemType,typename Comp,typename Input>
Input sub_vec(InputIterator first,InputIterator last,Input& at, const ElemType &val,Comp pred)//将参数Input改为引用
{
sort(first,last);
first=find_if(first,last,bind2nd(pred,val));
at.erase(first,last);
return at;
}
int main()
{
int ia[6]={12,2,4,32,7,1};
vector<int> ivec(ia,ia+6);
sub_vec(ivec.begin(),ivec.end(),ivec,6,greater<int>());//此处不需返回值
for(int ix=0;ix<ivec.size();ix++)
cout << ivec[ix] << " ";
cout << endl;
return 0;
}
[解决办法]
template <typename ElemType,typename Comp,typename Input>void sub_vec(Input& at, const ElemType &val,Comp pred){ sort(at.begin(),at.end()); typename Input::iterator first=find_if(at.begin(),at.end(),bind2nd(pred,val)); at.erase(first,at.end());}int main(){ int ia[6]={12,2,4,32,7,1}; vector<int>ivec(ia,ia+6); sub_vec(ivec,6,greater<int>()); for(int ix=0;ix<ivec.size();ix++) cout << ivec[ix] << " "; cout << endl; return 0;}