[英]std::for_each on container of pointers
In some class I have a hash_set
of pointers: 在某些类中,我有一个hash_set
:
std::hash_set<GameObject*> gameObjects;
I wish to iterate through all of them and call update. 我希望遍历所有这些对象并调用update。 With iterators this would be like this: 使用迭代器,将像这样:
for(std::hash_set<GameObject*>::iterator it = gameObjects.begin(), it_end = gameObjects.end(); it != it_end; ++it)
{
(*it)->update();
}
This is too much code; 这是太多的代码; I want to use std::for_each
. 我想使用std::for_each
。
If I had just hash_set<GameObject>
, this would look like this: 如果我只有hash_set<GameObject>
,则如下所示:
std::for_each(gameObjects.begin(), gameObjects.end(), std::mem_fun_ref(&GameObject::update));
or, if update was expecting a parameter, 或者,如果更新需要参数,
std::for_each(gameObjects.begin(), gameObject.end(), std::bind2nd(std::mem_fun_ref(&GameObject::update), deltaTime));
How would these both expressions look for the hash_set
of pointers? 这两个表达式如何寻找指针的hash_set
?
I am using MS VisualStudio 2010. 我正在使用MS VisualStudio 2010。
If you have a compiler which supports lambdas (C++11), you could use 如果您有支持lambdas(C ++ 11)的编译器,则可以使用
std::for_each(gameObjects.begin(), gameObjects.end(), [=](GameObject* o) {o->update(deltaTime);});
Using lambdas is a good option for many STL algorithms, but, as @phresnel points out, the range-based for loop (also C++11) is more concise in this case: 对于许多STL算法,使用lambdas是一个不错的选择,但是,正如@phresnel指出的,在这种情况下,基于范围的for循环(也是C ++ 11)更加简洁:
for (auto o : gameObjects)
o->update(deltaTime);
You can use the same code you have, but use mem_fun
instead of mem_fun_ref
您可以使用相同的代码,但使用mem_fun
而不是mem_fun_ref
std::for_each(gameObjects.begin(), gameObjects.end(),
std::mem_fun(&GameObject::update));
As an alternative to std::for_each
, if your compiler and policy allows for it, you can use C++' range based for : 作为std::for_each
的替代方案,如果您的编译器和策略允许这样做,则可以将C ++ 范围用于以下内容 :
for (auto p : gameObjects) p->update();
This feature was added with C++11, which is the current C++ standard. 当前的C ++标准C ++ 11中添加了此功能。 Not all compiler(-versions) may support it yet. 并不是所有的编译器(版本)都可以支持它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.