【问题标题】:lambda function predicate to use for find_if which compares compound type map element用于比较复合类型映射元素的 find_if 的 lambda 函数谓词
【发布时间】:2013-11-22 11:59:46
【问题描述】:

请看下面的sn-p代码:

typedef boost::tuple<std::string, int, std::string> TUPLE;
std::map<int, TUPLE> m;

std::find_if
    (
        m.begin(),
        m.end(),
        boost::lambda::bind
            (
                &std::map<int, TUPLE>::value_type::second_type::head,
                boost::lambda::bind
                (
                    &std::map<int, TUPLE>::value_type::second,
                    boost::lambda::_1
                )
            )
        ==
        "someString"
    );

我正在尝试为 find_if 创建一个谓词(使用 boost lambda)并将元组的第一个元素与字符串进行比较。但是,有什么方法可以使这项工作像这样:

typedef boost::tuple<std::string, int, std::string> TUPLE;
std::map<int, TUPLE> m;

std::find_if
    (
        m.begin(),
        m.end(),
        boost::lambda::bind
            (
                &std::map<int, TUPLE>::value_type::second_type::get<0>,
                boost::lambda::bind
                (
                    &std::map<int, TUPLE>::value_type::second,
                    boost::lambda::_1
                )
            )
        ==
        "someString"
    );

我将 second_type::head 更改为 second_type::get 但它无法编译。 我正在尝试创建将元组的第一个或第二个元素与某个字符串进行比较的谓词。

这是我遇到的错误之一:

错误 29 错误 C2780: 'const boost::lambda::lambda_functor>,detail::bind_tuple_mapper::type>> boost::lambda::bind(const Arg1 &)' : 需要 1 个参数 - 提供 2 个

有没有办法专门比较元组的第n个元素? (不只是头部) 我尝试将元组元素表示为结构,它可以工作,但如果有使用元组的方法,我将不胜感激。

旁注:由于编译器版本,我不能使用[](){} 表示法。

【问题讨论】:

    标签: c++ if-statement find predicate


    【解决方案1】:

    好吧,我不知道 boost,但是对于 C++11 lambda,它会是以下内容:

    typedef std::tuple<std::string, int, std::string> TUPLE;
    std::map<int, TUPLE> m;
    
    std::find_if(m.begin(), m.end(), [] (const std::pair<int, TUPLE>& v) {
        return v.second.get<1>() == "someString";
    });
    

    从 boost 文档中猜测,这将是:

    std::find_if(m.begin(), m.end(), 
        return boost::lambda::_1.second.second == "someString");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      相关资源
      最近更新 更多