【问题标题】:nested usage of boost::bind in boost::lambda not workingboost::lambda 中 boost::bind 的嵌套用法不起作用
【发布时间】:2013-09-05 17:22:32
【问题描述】:

我在 boost lambda 上的以下简单程序正在喷出以下错误:

maxInMap.cpp:29:71: instantiated from here /usr/include/boost/lambda/detail/function_adaptors.hpp:264:15: error: invalid initialization of reference of type ‘std::vector<int>&’ from expression of type ‘const std::vector<int>’

请帮助我理解这个问题,因为这将对我的整体 Boost Lambda 有所帮助

#include <map>

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

#include <boost/lambda/lambda.hpp>
#include <boost/lambda/if.hpp>
#include <boost/lambda/algorithm.hpp>
#include <boost/lambda/bind.hpp>

using namespace std ;
using namespace boost ;
using namespace boost::lambda ;

int main()
{
    map<int, vector<int> > intVecMap ;
    int vecSizes[] = {3, 6, 2, 9, 5, 8, 1, 7, 10, 4} ;
    for (int i = 0; i < 10; i++) 
        intVecMap[i] = vector<int>(vecSizes[i], i) ;

    map<int, vector<int> >::const_iterator itr =
        max_element(intVecMap.begin(), intVecMap.end(),
                    (bind(&vector<int>::size,
                          bind(&pair<int, vector<int> >::second, _1)) <
                     bind(&vector<int>::size,
                          bind(&pair<int, vector<int> >::second, _2)))) ;
    if (itr == intVecMap.end())
        cout << "Max Element function could not find any max :-(\n" ;
    else 
        cout << "Max Index = "<<(*itr).first<<" Size = "<<(*itr).second.size()<<endl ;
    return 0 ;
}

【问题讨论】:

    标签: c++ boost boost-bind boost-lambda


    【解决方案1】:

    该错误实际上与 Boost.Lambda 或 Boost.Bind 无关,这是问题所在:

                          bind(&pair<int, vector<int> >::second, _2)))) ;
    

    map&lt;int, vector&lt;int&gt; &gt;value_type 不是pair&lt;int, vector&lt;int&gt;&gt; 它是pair&lt;const int, vector&lt;int&gt;&gt;

    如果将pair&lt;int, 的两次出现都更改为pair&lt;const int,,它应该可以编译。

    map 具有 const 键类型的原因是为了防止您通过修改元素的键来使地图的顺序无效。)

    【讨论】:

    • 非常感谢 Jonathon,这确实是问题所在。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2011-02-08
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    相关资源
    最近更新 更多