passing struct member to function

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;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <string>
#include <iostream>

using namespace 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";
}


Thanks in advance for your help.
closed account (D80DSL3A)
Use a character code to identify which member?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void SearchString(string key, testNode* ptr, char memberCode)// memberCode = 'f', 'm' or 'l'
{
	int count = 0;
	
    while(ptr != NULL)
	{
		switch(memberCode)
		{
		case 'f':		
			if(ptr->firstName == key) count++;
			break;
		case 'm':		
			if(ptr->middleName == key) count++;
			break;
		case 'l':		
			if(ptr->lastName == key) count++;
			break;
		default:
			break;
		}
		ptr = ptr->next;
	}
	cout << key << " was found " << count << " times!!\n";
}

EDIT: Perhaps this is too simplistic?
Last edited on
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.
Topic archived. No new replies allowed.