如何在带有输入的地图元素方法上使用std :: for_each? [英] How to use std::for_each on a map element method with input?
问题描述
我有:
struct Mystruct
{
void Update(float Delta);
}
typedef std::map<int, Mystruct*> TheMap;
typedef TheMap::iterator TheMapIt;
TheMap Container;
并想这样做:
for(TheMapIt It = Container.begin(), Ite = Container.end(); It != Ite; ++It)
{
It->second->Update(Delta);
}
使用std::for_each
,该怎么做?
我想我可以声明如下函数:
I think I can declare function like:
void Do(const std::pair<int, Mystruct*> Elem)
{
Elem->Update(/*problem!*/); ---> How to pass Delta in?
}
或制作另一个结构:
struct Doer
{
Doer(float Delta): d(Delta) {}
void operator(std::pair<int, Mystruct*> Elem)
{
Elem->Update(d);
}
}
但这需要一个新的结构.
But this requires a new struct.
我要实现的是使用普通的std::for_each
以及std::bind_1st
,std::mem_fun
之类的东西,就像std::vector
一样,
What I wants to achieve is using plain std::for_each
with something like std::bind_1st
, std::mem_fun
like the way with std::vector
, is it possible?
请先考虑使用std
的方式,然后再使用boost
,谢谢!
Please consider using std
way before using boost
, thanks!
我已经引用了这个,但是它并没有提及带有输入的成员函数... 我将如何使用for_each删除STL映射中的每个值?
I've referenced this but it doesnt metion about member function with input... How would I use for_each to delete every value in an STL map?
推荐答案
这只是编码风格之间的一种折衷,for循环和for_each没有什么大的区别,下面是for循环以外的另外两种方法:
This is just a trade between coding style, for loop and for_each doesn't make big difference, below are two other approaches besides for loop:
如果您使用C ++ 11,则可以尝试使用lambda:
If you use C++11, could try lambda:
std::for_each(TheMap.begin(), TheMap.end(),
[](std::pair<int, Mystruct*>& n){ n.second->Update(1.0); });
或者在C ++ 03中,您可以向包装类添加一个成员函数,然后调用std::bind1st
和std::mem_fun
Or in C++03, you could add a member function to wrapper class then call std::bind1st
and std::mem_fun
struct MapWrapper
{
MapWrapper(int value=1.0):new_value(value) {}
void Update(std::pair<int, Mystruct*> map_pair)
{
map_pair.second->Update(new_value);
}
void setValue(float value) { new_value = value; }
float new_value;
std::map<int, Mystruct*> TheMap;
};
MapWrapper wrapper;
wrapper.setvalue(2.0);
std::for_each(wrapper.TheMap.begin(),
wrapper.TheMap.end(),std::bind1st(std::mem_fun(&MapWrapper::Update), &wrapper));
写一个函子不是一个坏选择,为什么反对呢?函子可提供更好的设计,因为它提供了清晰明了的目的.
Write a functor isn't a bad choice, why you are against it? A functor provides better design as it provides clean and clear purpose.
struct Doer
{
Doer(float Delta): d(Delta) {}
void operator()(std::pair<int, Mystruct*> e)
{
e.second->Update(d);
}
float d;
};
Doer doer(1.0);
std::for_each(wrapper.TheMap.begin(), wrapper.TheMap.end(), doer);
这篇关于如何在带有输入的地图元素方法上使用std :: for_each?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!