【问题标题】:Accessing member variables through boost lambda placeholder通过 boost lambda 占位符访问成员变量
【发布时间】:2011-01-20 08:56:54
【问题描述】:

我正在尝试使用 lambda 表达式打印 stl 映射中所有项目的第二个成员变量

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

但这不是编译。我基本上想取消引用占位符。知道我在这里缺少什么吗?

提前致谢!

【问题讨论】:

    标签: c++ variables lambda member


    【解决方案1】:

    std::map 会将const 添加到其密钥中;这是为了防止弄乱排序。你的配对应该是:

    std::pair<const int, int>
    

    就像 dirkgently 建议的那样,使用 value_type 始终获得正确的类型。使用 typedef 可以减轻冗长:

    typedef std::map<int, int> int_map;
    
    int_map::value_type::second
    

    【讨论】:

      【解决方案2】:

      试试:

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

      【讨论】:

      • 太好了,感谢 dirkgently 和 GMan,当结合编译器所说的内容时,这很有效并且很有意义。干杯!
      猜你喜欢
      • 2022-12-17
      • 2016-07-15
      • 2020-04-29
      • 1970-01-01
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-10
      相关资源
      最近更新 更多