更容易的方式来做回调的向量(或可能在STL的其他东西)? C ++ [英] Easier way to do callbacks for vectors (or maybe something else in the STL)? C++
问题描述
我在做一个简单的犯罪模拟游戏。
I'm making a simple crime sim game.
在整个过程中,我一直做同样的事情:
Throughout it I keep doing the same thing over and over:
// vector<Drug*> drugSack;
for (unsigned int i = 0; i < this->drugSack.size(); i++)
this->sell(drugSack[i]);
只是一个例子。我讨厌有所有这些环路的所有地方omg QQ,反正做类似的:
Just one example. I hate having all these for loops all over the place omg QQ, anyway to do something like:
drugSack->DoForAll((void*)myCallBack);
我不太熟悉STL。
推荐答案
开始了解stl算法的时间:
Time to start knowing the stl algorithms:
#include <algorithm>
...
std::for_each( drugSack.begin(), drugSack.end(),
std::bind1st( std::mem_fun_ptr( &ThisClass::Sell ), this ) );
想法是创建一个称为函子的对象, drugSack.begin(),drugSack.end()
中的每个元素。
The idea is to create an object, called a "functor", that can do a certain action for each of the elements in the range drugSack.begin(), drugSack.end()
.
此函数可以使用 mem_fun_ptr
等stl构造创建,从而使函数接受 ThisClass *
和 Drug *
参数,以及一个替换/绑定 Class * code>
。
This functor can be created using stl constructs like mem_fun_ptr
, resulting in a functor taking a ThisClass*
and a Drug*
argument, and a wrapper around it that will substitute/bind the Class*
for this
.
这篇关于更容易的方式来做回调的向量(或可能在STL的其他东西)? C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!