如何在带有输入的map元素方法上使用std :: for_each?

Mar*_*Mao 3 c++ stl map

我有:

struct Mystruct
{
    void Update(float Delta);
}

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

TheMap Container;
Run Code Online (Sandbox Code Playgroud)

并且想做:

for(TheMapIt It = Container.begin(), Ite = Container.end(); It != Ite; ++It)
{
    It->second->Update(Delta);
}
Run Code Online (Sandbox Code Playgroud)

使用std::for_each,怎么做?

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

void Do(const std::pair<int, Mystruct*> Elem)
{
    Elem->Update(/*problem!*/); ---> How to pass Delta in?
}
Run Code Online (Sandbox Code Playgroud)

或者制作另一个结构:

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

    void operator(std::pair<int, Mystruct*> Elem)
    {
        Elem->Update(d);
    }
}
Run Code Online (Sandbox Code Playgroud)

但这需要一个新的结构.

我想要实现的是使用简单std::for_each的东西std::bind_1st,std::mem_fun就像这样std::vector,有可能吗?

std在使用前考虑使用方式boost,谢谢!

我已经引用了这个,但它没有关于成员函数的输入... 如何使用for_each删除STL映射中的每个值?

bil*_*llz 6

这只是编码风格之间的交易,for循环和for_each没有太大区别,下面是除了循环之外的另外两种方法:

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

std::for_each(TheMap.begin(), TheMap.end(), 
              [](std::pair<int, Mystruct*>& n){ n.second->Update(1.0); });
Run Code Online (Sandbox Code Playgroud)

或者在C++ 03中,您可以向包装类添加成员函数,然后调用std::bind1ststd::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));
Run Code Online (Sandbox Code Playgroud)

写一个仿函数不是一个糟糕的选择,为什么你反对呢?仿函数提供更好的设计,因为它提供干净和清晰的目的.

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);
Run Code Online (Sandbox Code Playgroud)