c++ - 使用 std::map 的 Miniheap lambda

标签 c++ c++11 dictionary lambda cin

对于一项任务,我们必须制作一个 MiniHeap 类,该类使用 std::map 将用户的输入命令连接到 lambda。这些命令使用基本的东西(push_back、pop_back、accumulate 等)操作 std::vector。我唯一的问题是添加功能。用户必须能够输入“add 123”,以便“123”在 vector 中被推回。我当前的代码:

class MiniHeap
{
public:
    MiniHeap()
    {
    // Make an add lambda that  recognizes part of it's key as "add" and proceeds to recognize it's numerical part, convert it to an int and then adds it to m_Vector.
    std::function<void()> add = [&](){};
    std::function<void()> list = [&](){for (int i = 0; i < m_Vector.size(); ++i){ std::cout << m_Vector.at(i) << std::endl; }};
    std::function<void()> pop = [&](){m_Vector.pop_back(); };
    std::function<void()> sum = [&](){std::cout << std::accumulate(m_Vector.begin(), m_Vector.end(), 0) << std::endl; };

    }
    void Execute(const std::string & command)const
    {
        auto cmd = m_Commands.find(command);
        if (cmd != m_Commands.end())
        {
            cmd->second();
        }
    }
private:
    std::vector<int> m_Vector;
    std::map<std::string, std::function<void()>> m_Commands;
};

int main()
{
    //MiniHeap
    MiniHeap heap;
    for (;;)
    {
        std::string command;
        std::cout << "> ";
        std::cin >> command;
        heap.Execute(command);
    }

    std::cin.get();
    return 0;
}

问题:我只被允许修改 MiniHeap 类的构造函数。我已经在 MiniHeap 构造函数中评论了我遇到问题的部分。 std::find 如何处理包含部分“add”和数值的字符串?

非常感谢。

最佳答案

难点可能在于您假设指令:

std::cin >> command;

将一次性读取整个输入。它实际上会停在第一个空白处。知道了这一点,您应该能够实现 add,使用与上述相同的方法来获取输入流中的剩余数字。

关于c++ - 使用 std::map 的 Miniheap lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28656728/

相关文章:

c++ - 除法和乘法 std::chrono::durations

c++ - 使用 Ceres 优化多维函数

c++ - 如何调试 'Stack smashing detected' ?

c++ - VS2005 : How to compile projects as if it was VS6?

android - 在 Android 设备中运行 C++ 程序

c++ - make/gmake 的条件依赖

c++ - 为什么要把 std::lock 放在 std::lock_guard 之前

python - 如何查看玩家是否回答了与该值的键对应的值

swift - 找不到 Swift 字典 "keys"属性的内部实现

python - 用多种推导式填充字典