【问题标题】:Miniheap lambda using std::map使用 std::map 的 Miniheap lambda
【发布时间】:2015-02-22 10:20:42
【问题描述】:

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

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”部分和数值的字符串?

非常感谢。

【问题讨论】:

  • 您需要输入名称,例如"add" 和相应的功能,例如add 进入地图 - 在构造函数中应该是可行的。

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


【解决方案1】:

难点可能是你假设指令:

std::cin >> command;

将一口气读取整个输入。它实际上会停在第一个空白处。知道了,应该可以实现add了,用和上面一样的方法来获取输入流中的剩余数。

【讨论】:

  • 我确实认为它会读取整行。知道我需要做的就是弄清楚如何在那里获得剩余的数字。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-23
相关资源
最近更新 更多