C++ 使用 Map 中的参数调用函数

标签 c++

我正在玩弄一些我以前用来从 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/

相关文章:

C++ 在方法中实例化一个类,然后从不同的方法更改成员变量?

c++ - "*&"在一起是什么意思?

c++ - 使用 MITK 绘制点/线

c++ - 经过最后一个数组元素末尾的指针是否等于经过整个数组末尾的指针?

C++ 引用包装器作为函数参数

c++ - 如何防止 Gnome 在执行 alt-tab 时显示两个窗口? (C++ qt 应用程序)

c++ - 将 2 个项目插入 vector 中

c++ - 从渐变中获取中间色

c++ - MPI 使用 MPI_Alltoallv 发送动态大小的数组

c++ - 整数作为假人的 char*