Issue
I am using a function to print out data from a linked list, the list Nodes have 2 variables which could be accessed, data or index. I want to add a parameter to the print() function that allows the user to call the variables name within the Node that they want to be outputted, I've heard of passing by reference and I'm pretty sure this is what I want to do but haven't found any resources that actually work for my code.
(simply I want to pass a variable name to a function).
here is my code:
struct Node {
int data;
int index;
Node *next;
}
Node *_current;
Node *_next;
Node *_head;
Node *_temp;
Node *_tail;
Node *_last;
// all this is handled correctly
void print(*variable name*) {
Node *n = _head;
while (n->next != nullptr) {
std::cout << n-> *variable name* << std::endl;
n = n->next;
}
}
p.s: variable name is not necessarily a pointer but just (literally) referring to the variable name parameter I want to add.
this code works if I swap out variable name to 'std::cout << n->data <<...' and runs without any other issues. (btw Whole code isn't provided just the parts needed to explain what I want to change)
any helpful information is greatly appreciated, Thank you in advance. :)
Solution
p.s: variable name is not necessarily a pointer
But it is a pointer. A member pointer, specifically:
void print(int Node::*member) {
Node *n = _head;
while (n->next != nullptr) {
std::cout << n->*member << std::endl;
n = n->next;
}
}
It would get invoked as either
print(&Node::data);
or
print(&Node::index);
Answered By - Sam Varshavchik Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.