c++ - Variable or field declared as void -
c++ - Variable or field declared as void -
i have read posts same problem, haven't found problem in solutions.
i want wirte simple linked list generic content:
but written error "variable or field >>insert<< void declared" , each method except main.
i hope can help me, thanks
#include<iostream> #include<string> //edit:#include"liste.t" waste former test using namespace std; template <typename t> struct element{ t value; element *next; element(t v, element *n) : value(v), next(n) { } }; template <typename t> void insert(element, t, int (*eq)(t,t)); template <typename t> void remove(element, t, int (*eq)(t,t)); void print(element); template <> int equal<string>(t, t); template <typename t> int equal(t, t); int main(){ int (*eq)(int,int) = equal; element* head=null; insert(head, 2, eq); insert(head, 5, eq); insert(head, 1, eq); print(head); remove(head, 2, eq); print(head); } template <typename t> void insert(element* &rp, t v, int (*eq)(t, t)){ if(rp!=null){ if(eq(rp->value, v)>=0){ rp = new element(v, rp); }else{ insert(rp->next, v, eq) } }else{ rp = new element(v, null); } } template <typename t> void remove(element * &rp, t v, int (*eq)(t, t)){ if(rp!=null){ if(eq(rp->value, v)==0){//v element *tmp = rp; rp=rp->next; delete tmp; remove(rp,v, eq); }else{ remove(rp->next, v, eq); } } } void print(element *p){ while(p){ cout<<p->value << " "; p=p->next; } cout << endl; } template <> int equal<string>(t a, t b){ int min=0; if(length(a)<length(b)){ min = length(a); }else{ min=length(b); } for(int i=0; i< min; i++){ if(a[i]<b[i]) homecoming -1; if(a[i]>b[i]) homecoming 1; } homecoming 0; } template <typename t> int equal(t a, t b){ if(a<b) homecoming -1; if(a>b) homecoming 1; homecoming 0; }
note: should utilize std::list
or std::forward_list
instead of rolling out own container.
in function declarations you'll encounter compile error using element without template parameter (this error asking about):
class="lang-cpp prettyprint-override">template <typename t> void insert(element, t, int (*eq)(t,t)); ^
this should utilize element<t>
instead , should take in pointer element.
template <typename t> void insert(element<t>*, t, int (*eq)(t,t));
the print
function needs template:
template <typename t> void print(element<t> *p)
it appears trying specialize equals strings using template specialization. declaration should read:
template <> int equal<string>(string, string);
because t not declared in context.
i need stress 1 time again should really, consider using std::list
or std::forward_list
instead of rolling out own container. there no need reinvent wheel.
c++
Comments
Post a Comment