C++ 如何在带有输入的映射元素方法上使用std::for_each?

C++ 如何在带有输入的映射元素方法上使用std::for_each?,c++,stl,map,C++,Stl,Map,我有: struct Mystruct { void Update(float Delta); } typedef std::map<int, Mystruct*> TheMap; typedef TheMap::iterator TheMapIt; TheMap Container; 如何使用std::for_each 我想我可以声明如下函数: void Do(const std::pair<int, Mystruct*> Elem) {

我有:

struct Mystruct
{
    void Update(float Delta);
}

typedef std::map<int, Mystruct*> TheMap;
typedef TheMap::iterator         TheMapIt;

TheMap Container;
如何使用
std::for_each

我想我可以声明如下函数:

void Do(const std::pair<int, Mystruct*> Elem)
{
    Elem->Update(/*problem!*/); ---> How to pass Delta in?
}
void Do(const std::pair Elem)
{
元素->更新(/*问题!*/);-->如何传递增量?
}
或者制作另一个结构:

struct Doer
{
    Doer(float Delta): d(Delta) {}

    void operator(std::pair<int, Mystruct*> Elem)
    {
        Elem->Update(d);
    }
}
struct-Doer
{
Doer(float Delta):d(Delta){}
void运算符(std::pair Elem)
{
元素->更新(d);
}
}
但这需要一个新的结构

我想要实现的是使用普通的
std::for_each
std::bind_1st
std::mem_fun
std::vector
一样,这可能吗

在使用<代码> Boost 之前,请考虑使用<代码> STD<代码>代码,谢谢!p> 我已经引用了这个,但它不包含关于输入的成员函数。。。


这只是编码风格之间的一种折衷,for循环和for_各不相同,下面是除for循环之外的两种其他方法:

如果您使用C++11,可以尝试lambda:

std::for_each(TheMap.begin(), TheMap.end(), 
              [](std::pair<int, Mystruct*>& n){ n.second->Update(1.0); });
写一个函子不是一个坏选择,为什么你反对它?函子提供了更好的设计,因为它提供了清晰的目的

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);
struct-Doer
{
Doer(float Delta):d(Delta){}
void运算符()(标准::对e)
{
e、 第二次->更新(d);
}
浮动d;
};
实干家(1.0);
std::for_each(wrapper.TheMap.begin()、wrapper.TheMap.end()、doer);

只是想指出lambda可以用更好的语法编写,您已经开始为地图定义typedef了。下一步是使用ValueType,这样您就不必记住映射元素是std::pairs,也不必写出模板参数

 using namespace std;
 for_each(begin(Container), end(Container), 
          [](TheMap::ValueType& n){ n.second->Update(1.0); });

更易于阅读,并允许您更改某些细节,而无需将这些更改传播到大量不同的地方

您好:1.0不能是常量,必须传入。我不想为这个任务制作新的课程。可能吗?谢谢:)对于_,每个第三个参数都是一元函数,这意味着它不能接受额外的参数。您可以将成员函数添加到MapWrapper以动态设置值吗?查看我的更新答案。我会选择
struct Doer
这是一个更好的选择。您可以使用
std::bind1st
处理二进制函数,但我只是不知道如何处理
map
元素,因为它不是
vector
。我知道如何在
(*it)->update(Delta)
上使用
std::bind1st
,但现在它是
(*it)。第二个->update(Delta)
:(我只想指出,
TheMap
是一个类型名,实例名为
Container
)。
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);
 using namespace std;
 for_each(begin(Container), end(Container), 
          [](TheMap::ValueType& n){ n.second->Update(1.0); });