For an assignment we have to make a MiniHeap class that uses an std::map to connect the user's input commands to lambdas. These commands operate an std::vector with basic things (push_back, pop_back, accumulate, etc.). The only problem I have is the add function. The user must be able to input "add 123" so "123" is pushed back in the vector. My current code:
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;
}
The catch: I am only allowed to modify the constructor of the MiniHeap class. I've commented the part which I'm having trouble with up in the MiniHeap constructor. How can the std::find work on a string that has part "add" and a numerical value?
Many thanks in advance.
Aucun commentaire:
Enregistrer un commentaire