2010-10-05 135 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值。