2010-10-05 133 views
6

我正在使用C++ 0x lambda表达式修改映射的值。如何通过C++的参考传递Lambda表达式参数0x

但是,难以通过引用传递映射迭代器。

如果我只是通过迭代器,值如:[](std::pair<TCHAR, int > iter)编译好,但值不会在地图上更新。

如果我试图通过引用传递迭代器,如[](std::pair<TCHAR, int >& iter) VS2010的编译器抱怨说,它

cannot convert paramater from 'std::pair<_Ty1,_Ty2>' to 'std::pair<_Ty1,_Ty2> &' 

这里是代码。欣赏关于如何使用lambda表达式修改std :: map对象的信息。

#include <tchar.h> 
#include <map> 
#include <algorithm> 
#include <vector> 
int _tmain(int argc, _TCHAR* argv[]) 
{ 
    typedef std::map<TCHAR, int > Map; 

    Map charToInt; 

    charToInt[_T('a')] = 'a'; 
    charToInt[_T('b')] = 'b'; 
    charToInt[_T('c')] = 'c'; 
    charToInt[_T('d')] = 'd'; 

    std::for_each(charToInt.begin(), charToInt.end(), [](std::pair<TCHAR, int >& iter) 
    { 
     int& val = iter.second; 
     val++; 
    }); 

    return 0; 
} 

谢谢

回答

4

的问题是,你不能修改地图的关键。

std::for_each(charToInt.begin(), charToInt.end(), [](std::pair<const TCHAR, int>& iter) 

将工作,因为它使用const TCHAR

编辑:

作为@大卫和其他海报指出的那样,你会过得更好使用Map::value_type&这是在这种情况下std::pair<const TCHAR, int>&一个typedef,因为如果你以后更改类型的地图,你是关闭使用你也不需要改变循环代码。

仅供参考,以下是完整的错误信息,在这里你可以看到它正试图两种不同类型的对,一个与TCHAR,其他与const TCHAR之间的转换...

cannot convert parameter 1 from 'std::pair<_Ty1,_Ty2>' to 'std::pair<_Ty1,_Ty2> &' 
    with 
    [ 
     _Ty1=TCHAR, 
     _Ty2=int 
    ] 
    and 
    [ 
     _Ty1=const TCHAR, 
     _Ty2=int 
    ] 
    and 
    [ 
     _Ty1=TCHAR, 
     _Ty2=int 
    ] 
+3

+1用于诊断hte问题,但更好的解决方案是使用'Map :: value_type&',因为意图更清晰且不易出错。 – 2010-10-05 11:15:58

+0

谢谢 - 这些建议正在起作用。 – 2010-10-06 00:51:18

1

你是没有通过一个迭代器,你是尝试传递给map::value_type的引用。发布的代码甚至不应该编译。通过map::value_type&,那么程序必须递增存储在地图中的int值。