我有一张 map ,我想在其中调用每个数据类型对象的成员函数。我还知道如何在任何序列上执行此操作,但是是否可以在关联容器上执行此操作?
我能找到的最接近的答案是:Boost.Bind to access std::map elements in std::for_each .但是我不能在我的项目中使用 boost 那么,是否有我缺少的 STL 替代方案来 boost::bind?
如果不可能,我想为指向数据对象的指针创建一个临时序列,然后在其上调用 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));
它看起来太模糊了,我不太喜欢它。有什么建议吗?
最佳答案
C++11 允许你这样做:
for (const auto& kv : myMap) {
std::cout << kv.first << " has value " << kv.second << std::endl;
}
C++17 允许你这样做:
for (const auto& [key, value] : myMap) {
std::cout << key << " has value " << value << std::endl;
}
使用 structured binding .
更新:
如果您不想修改 map ,则 const auto 会更安全。
关于c++ - 在 map 元素上使用 for_each,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2850312/