c++ - boost::lambda 中 boost::bind 的嵌套用法不起作用

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

我在 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 ;
}

最佳答案

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

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

value_typemap<int, vector<int> >不是 pair<int, vector<int>>它是 pair<const int, vector<int>>

如果您更改两次出现的 pair<int,pair<const int,它应该编译。

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

关于c++ - boost::lambda 中 boost::bind 的嵌套用法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18642343/

相关文章:

c++ - boost 不相交集:如何检索集?

c++ - 正则表达式和 boost

c++ - 识别 boost::shared_ptr<boost::thread> 中的对象

c++ - 使用类的非模板版本作为父类

c++ - 使用Windows运送linux

c++ - 如何在 C++ 中处理大小为 1,000,000,000 的数组?

c++ - 用 boost::assign::map_list_of 填充 boost::function 的 std::map

c++ - 有没有办法在 Visual Studio 中列出库依赖项?

c++ - gSOAP 多线程

c++:可以使用boost::bind将成员函数转换为预期的函数指针签名吗?