开发者

Accessing member variables through boost lambda placeholder

开发者 https://www.devze.com 2022-12-21 05:40 出处:网络
I\'m trying to print the second member varia开发者_开发知识库ble of all items in an stl map using a lambda expression

I'm trying to print the second member varia开发者_开发知识库ble 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?

Thanks in advance!


Try:

for_each(theMap.begin(), theMap.end(), 
         cout << bind(&map<int, int>::value_type::second, _1) << constant(" "));


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>

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号