小编典典

在地图元素上使用for_each

algorithm

我有一个地图,我想在该地图上对每个数据类型对象成员函数进行调用。我仍然知道如何按任何顺序执行此操作,但是是否可以在关联容器上执行此操作?

我能找到的最接近答案是:Boost.Bind访问std :: for_each中的std ::map元素。但是我不能在项目中使用boost,所以是否存在我缺少boost ::bind的STL替代方法?

如果不可能的话,我考虑过为数据对象的指针创建一个临时序列,然后在其上调用for_each,如下所示:

class MyClass
{
public:
 void Method() const;
}

std::map<int, MyClass> Map;
//...

std::vector<MyClass*> Vector;
std::transform(Map.begin(), Map.end(), std::back_inserter(Vector), std::mem_fun_ref(&std::map<int, MyClass>::value_type::second));
std::for_each(Vector.begin(), Vector.end(), std::mem_fun(&MyClass::Method));

它看起来太模糊了,我不太喜欢。有什么建议?


阅读 293

收藏
2020-07-28

共1个答案

小编典典

您可以遍历一个std::map对象。每个迭代器都指向一个std::pair<constT,S>位置TS并且与您在上指定的类型相同map

这将是:

for (std::map<int, MyClass>::iterator it = Map.begin(); it != Map.end(); ++it)
{
  it->second.Method();
}

如果仍要使用std::for_each,请传递一个以a std::pair<const int, MyClass>&作为参数的函数。

例:

void CallMyMethod(std::pair<const int, MyClass>& pair) // could be a class static method as well
{
  pair.second.Method();
}

并将其传递给std::for_each

std::for_each(Map.begin(), Map.end(), CallMyMethod);
2020-07-28