本文介绍了通过boost lambda占位符访问成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图使用lambda表达式打印stl地图中所有项目的第二个成员变量
I'm trying to print the second member variable of all items in an stl map using a lambda expression
map<int, int> theMap;
for_each(theMap.begin(), theMap.end(),
cout << bind(&pair<int, int>::second, _1) << constant(" "));
但这不是编译。我本质上想取消引用占位符。
but this is not compiling. I essentially want to de-reference the placeholder. Any idea what I'm missing here?
提前感谢!
推荐答案
std :: map
将向其键添加 const
这是为了防止弄乱排序。您的对应为:
std::map
will add const
to its key; this is to prevent messing up the ordering. Your pair should be:
std::pair<const int, int>
像dirkgently建议,使用 value_type
总是得到正确的类型。使用typedef可以减轻冗长性:
Like dirkgently suggests, use the value_type
to always get the correct type. The verbosity is alleviated with a typedef:
typedef std::map<int, int> int_map;
int_map::value_type::second
这篇关于通过boost lambda占位符访问成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!