c++ - linked lists and function pointers -
i trying learn function pointers , linked lists.
in class(as private) have
int (*m_pointertofunction)(int);
and
void list::apply_all( int (*pointertofunction) (int)){ m_pointertofunction = pointertofunction; }
and
int triple(int i) { return 3*i; }
which called list l2 with
l2.apply_all(triple);
what part missing in here? doesn't seem nodes in list.
edit: problem solved! comments , answer, never did nodes. iterates through list , works fine, :)
void list::apply_all( int (*pointertofunction) (int)){ node *temp = head; while(temp){ temp->value = pointertofunction(temp->value); temp = temp->next; } }
there's no need store function pointer in apply_all()
method. rather, need setup loop iterates on each element in list, , calls function pointer each one. judging triple()
function, want store result in list too, or else won't anything.
it's hard give example code without knowing how rest of list class structured. though, you'd put in loop inside apply_all()
:
nodevalue = pointertofunction(nodevalue);
in case you're not aware, c++ standard template library includes of functionality already. there's std::list
class, along functions std::transform()
, std::for_each()
can apply function pointers (or other callables) each element.
you might want @ std::function
template, introduced in c++11. makes function pointers lot easier work with!
Comments
Post a Comment