Ok so I've tried searching for an answer to this but I can't seem to find anything like it. I'm trying to write a search function for a linked list as generic as possible. I want to be able to pass in the key to be searched for, the head of the list, and which member of the struct to search within. The problem is I don't know how to pass which member I want to search within to the function. Here is my general idea with the part I'm not sure how to do in caps. Let's assume the CreateList function create's a linked list of 100 full names with the last next pointer pointing to NULL;
#include <string>
#include <iostream>
usingnamespace std;
struct testNode
{
string firstName;
string middleName;
string lastName;
testNode* next;
};
void SearchString(string Key, testNode* ptr, MEMBER_I_WANT_TO_BE_ABLE_TO_PASS_IN);
int main()
{
string key;
testNode* head;
head = CreateList();
cout << "What name would you like to search for: ";
getline(cin, key);
/*I want to be able to pass in the key, the head of the linked list as
* well as which member of the struct to search within
*/
SearchString(key, head, MEMBER_I_WANT_TO_TO_PASS_IN is first);
SearchString(key, head, MEMBER_I_WANT_TO_TO_PASS_IN is middle);
SearchString(key, head, MEMBER_I_WANT_TO_TO_PASS_IN is last);
}
void SearchString(string key, testNode* ptr, MEMBER_I_WANT_TO_BE_ABLE_TO_PASS_IN)
{
int count;
count = 0;
while(ptr != NULL)
{
if(ptr->MEMBER_I_WANT_TO_TO_PASS_IN == key)
{
count++;
}
ptr = ptr->next;
}
cout << key << " was found " << count << " times!!\n";
}
Interesting, I hadn't thought of something like that (I sometimes over complicate things lol) but I like that idea. It's probably the method I'll end up using but I'm still curious as to whether what I'm asking is possible some how. Thanks for the suggestion.