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

How to use std::for_each on a map element method with input?

本文关键字:std 方法 for each 元素 input map      更新时间:2023-10-16

我有:

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,如何做到这一点?

我想我可以这样声明函数:

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);
    }
}

但是这需要一个新的结构体

我想要实现的是使用普通的std::for_eachstd::bind_1st, std::mem_funstd::vector的方式,是可能的吗?

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

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

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

如果你使用c++ 11,可以试试lambda:

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

或者在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));
写一个函子不是一个坏的选择,为什么你反对它?函子提供了更好的设计,因为它提供了干净和明确的目的。
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);

只是想指出可以用更好的语法来编写lambda,通过为映射定义typedef,您已经开始了这条路。下一步是使用ValueType,这样您就不必记住map元素是std::对,也可以避免必须写出模板参数。

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

更容易阅读,并且允许您更改一些细节,而不必将这些更改传播到大量不同的地方。