我正在玩弄一些我以前用来从 map 调用无参数的 void 函数的代码。但是,我似乎无法弄清楚如何将参数传递给我存储在 map 中的函数。
此代码应显示一个菜单,例如:
1. Edit Record
2. Delete Record
3. Select Another Record
q. Quit
当您选择 1、2、3 或“q”时,应执行 map 中的相应操作。
这是目前的代码:
void DisplaySelectedRecordOptions(Record &rec)
{
struct SelectedRecordOptions
{
string option;
function<void()> action;
};
static const map <string, SelectedRecordOptions> SelectedRecordOptionsTable
{
{ "1",{ "Edit Record", []() { EditRecord(rec); } } },
{ "2",{ "Delete Record", []() { cout << "WORK IN PROGRESS\n"; } } },
{ "3",{ "Select Another Record", []() { cout << "WORK IN PROGRESS\n"; } } },
{ "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();
}
我在尝试运行时遇到以下错误:
an enclosing-function local variable cannot be referenced in a lambda body unless it is in the capture list
这是我想尝试在 map 中实现的 EditRecord 函数:
void EditRecord(Record &rec)
{
string description;
string username;
string password;
cout << "Description: ";
getline(cin, description);
cout << "Username: ";
getline(cin, username);
cout << "Password: ";
getline(cin, password);
rec.description = description;
rec.userName = username;
rec.password = password;
}
最佳答案
只需让您的 lambda 捕获使用的变量。简单的方法是这样的
[&]() { EditRecord(rec); }
&
使您的 lambda 捕获所有变量通过引用。有其他选择,这就是默认情况下不会发生这种情况的原因。你可以research these for yourself .
关于C++ 使用 Map 中的参数调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55371233/