如何在带有input的map元素方法上使用std::for_each
How to use std::for_each on a map element method with input?
我有:
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_each
与std::bind_1st
, std::mem_fun
像std::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::bind1st
和std::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); });
更容易阅读,并且允许您更改一些细节,而不必将这些更改传播到大量不同的地方。
相关文章:
- 使用std::函数映射对象方法
- 初始化具有非默认构造函数的std::数组项的更好方法
- std::atomic和std::condition_variable wait,notify_*方法之间的区别
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 为什么 std::span 缺少 cbegin 和 cend 方法?
- 使 std::vector 分配对齐内存的现代方法
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 如何访问存储在 std::variant 中的类的方法
- C++ assigment std::list:<typename>:itrator 在 main 中工作,但在方法中它不起作用
- 我无法使用C++指针指向类方法返回的 std::vector
- 在自定义 std::vector-like 容器中处理指针和非指针模板类型的最佳方法是什么?
- 静态 std::map instatiation 在类的方法中调用构造函数吗?
- C++:std::ofstream 方法 open() 在第二次迭代时擦除打开的 ifstream 文件
- 在 std::vector<无符号字符中存储任意数据的方法>
- 将 std:set<int32_t> 复制到 std::set <uint32_t>的好方法
- std::bind,无法让具有单个参数的方法工作
- 解决错误使用std方法/类时std标头中的错误
- 包装数据的STD方法
- 用STD方法对两个级数求和