Calling functions from a map

So I am trying to write a menu driven program. I have the menu down and displays just how I want it. But I was wondering if there is a way to call functions from within a map?

I have seen examples using lambdas but that is a little over my head at this point. Are there any alternatives to calling functions from a map?

Here is my code so far:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  int main()
{
	map<string, string> menu;
	menu.insert(pair <string, string>("1", "Option1"));
	menu.insert(pair <string, string>("2", "Option2"));
	menu.insert(pair <string, string>("3", "Option3"));

	map<string, string>::iterator it;

	for (it = menu.begin(); it != menu.end(); ++it)
	{
		cout << it->first << ". " << it->second << "\n";
	}

	return 0;
}
Last edited on
What do you mean by "from within"?
So, a little history...

I was using the following code. It does what I want. I had help with it and kinda just threw it together until it was working. Not really ideal. So, I went back to the basics tried building up again, thinking "there has got to be a more simple way."

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
void DisplaySelectedRecordOptions(Record &rec)
{
	struct SelectedRecordOptions
	{
		string option;
		function<void()> action;
	};

	const map <string, SelectedRecordOptions> SelectedRecordOptionsTable
	{
		{ "1",{ "Edit Record", [&]() { EditRecord(rec); } } },
		{ "2",{ "Delete Record", []() { cout << "WORK IN PROGRESS\n"; } } },
		{ "3",{ "Select Another Record", []() { DisplayAllRecords(GetRecords()); SearchRecords(GetRecords()); } } },
		{ "q",{ "Quit", []() { cout << "Quit" << "\n";  } } }
	};

	for (auto const& x : SelectedRecordOptionsTable)
	{
		cout << x.first << ". " << (x.second).option << "\n";
	}

	string input;

	while (SelectedRecordOptionsTable.count(input) == 0)
	{
		input = GetInput();
	}

	SelectedRecordOptionsTable.at(input).action();
}
A std::map can be used to store function pointers.

https://stackoverflow.com/questions/2136998/using-a-stl-map-of-function-pointers

If you currently find lambdas hard to understand, function pointers are going to be much the same.

That doesn't mean you shouldn't try to pull your brain up to them with practice, a bit of a challenge is a good thing.
What you have there is std::function objects: http://www.cplusplus.com/reference/functional/function/function/

std::function has more syntactic sugar than raw function pointer.
Topic archived. No new replies allowed.