因此,我首先进行了合理的Google搜索,但所有解决方案都显得过于复杂。所以,我想我会在这里问,看看这个任务是否真的需要我遇到过的那种方法...如何实现一个简单的事件队列?
因此,说我有一个Event
类。我希望它有一个time
变量和一个functionToExecuteAtTime
函数指针/变量/魔术代码片段,可以让我将任何旧函数传递给这个类。
另外,我希望事件按照时间顺序排列,并执行它们“携带”的功能。但忘记这个现在
像这样的东西......
class Agent
{
public:
int id;
float cash;
Agent::Agent
{
cash = 100;
}
}
class uberSystem
{
public:
float assets;
int supplyOfDeadlyPoison;
float poisonCost;
std::vector<Agent> agents;
uberSystem::uberSystem
{
assets = 100000;
supplyOfDeadlyPoison = 100000;
poisonCost = 8;
for(int i = 0; i < 100; i++)
{
Agent newAgent;
newAgent.id = i;
agents.push_back(newAgent)
}
}
};
class Event
{
public:
int time;
SOMETHING_THAT_LETS_ME_HOLD_FUNCTIONS myFunction;
Event::Event(int t, SOMETHING_THAT_LETS_ME_HOLD_FUNCTIONS func)
{
time = t;
myFunction = func;
}
}
int uselessFunction()
{
return 42;
}
void buyPoisonAndKillAgent(Agent &myAgent, uberSystem &mySystem)//obviously not good...
{
myAgent.cash -= mySystem.poisonCost;
mySystem.assets += mySystem.poisonCost;
mySystem.agents.erase(mySystem.agents.begin()+myAgent.id);
mySystem.supplyOfDeadlyPoison -= 1;
}
int main()
{
uberSystem newSystem;
// Event newEvent(100, uselessFunction());//make a new event
Event newEvent(100, buyPoisonAndKillAgent(newSystem.agents[5], newSystem));
newEvent.myFunction;//run the bloody function
return 0;
}
好了,所以看起来像极一厢情愿现在我键入它。那么,我怎么能做到这一点?函数指针是否要走?还是有一些更好的办法,我不知何故设法找不到?
哦,显然我的确有std::function
可用......毕竟我并没有处于石器时代!
谢谢!
那么[std :: deque>](http://en.cppreference.com/w/cpp/container/deque)呢? –
2014-10-03 08:24:48
std :: function可以做到这一点,我建议你避免函数指针。 :) – Melkon 2014-10-03 08:27:34
“时间”是实时的还是模拟的?或者它只是用来订购事件? – MatthiasB 2014-10-03 08:30:00