在地图元素使用的for_each的 [英] Use of for_each on map elements
问题描述
我有一个地图,我想执行的每个数据类型的对象的成员函数的调用。我还不知道如何做到这一点的任何序列,但,是有可能做到这一点的一个关联容器?
I have a map where I'd like to perform a call on every data type object member function. I yet know how to do this on any sequence but, is it possible to do it on an associative container?
最接近的答案,我能找到的是这样的:<一href="http://stackoverflow.com/questions/2311752/boost-bind-to-access-stdmap-elements-in-stdfor-each">Boost.Bind访问中的std :: for_each的的std ::地图元素。但我不能在我的项目,所以使用boost,有一个STL的替代方案,我失去了提高::绑定?
The closest answer I could find was this: Boost.Bind to access std::map elements in std::for_each. But I cannot use boost in my project so, is there an STL alternative that I'm missing to boost::bind?
如果没有可能,我想创造的三分球一个临时序列的数据对象,然后调用的for_each就可以了,是这样的:
If not possible, I thought on creating a temporary sequence for pointers to the data objects and then, call for_each on it, something like this:
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));
这看起来太模糊处理的,我真的不喜欢它。有什么建议?
It looks too obfuscated and I don't really like it. Any suggestions?
推荐答案
您可以通过的std ::地图
对象迭代。每个迭代器将指向的std ::对&LT;常量T,S&GT;
,其中 T
和取值
,你在你的地图中指定的同类型
。
You can iterate through a std::map
object. Each iterator will point to a std::pair<const T,S>
where T
and S
are the same types you specified on your map
.
下面这将是:
for (std::map<int, MyClass>::iterator it = Map.begin(); it != Map.end(); ++it)
{
it->second.Method();
}
如果你仍然想使用的std :: for_each的
,传递一个函数,它接受一个的std ::对&LT; const int的,MyClass的&GT;&放;。
作为参数,而不是
If you still want to use std::for_each
, pass a function that takes a std::pair<const int, MyClass>&
as an argument instead.
例如:
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);
这篇关于在地图元素使用的for_each的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!