开发者

How to pass Lambda expression parameter by Reference for C++0x

I am using a C++0x lambda expression to modify values of a map.

However, having difficulty passing the map iterator by reference.

If I just pass the iterator, by value such as: [](std::pair<TCHAR, int > iter) it compiles fine, but the values does not get updated in the map.

If I try to pass the iterator by reference, such as [](std::pair<TCHAR, int >& iter) the VS2010 compiler complains that it

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

Here is the code. Appreciate information on how the std::map objects can be modified using the lambda expressions.

#include <tchar.h>
#include <map>
#include <algorithm>
#include <vector>
int _tmain(int argc, _TCHAR*开发者_JS百科 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;
}

Thank you


The problem is that you are not allowed to modify the key of the map.

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

Will work because it uses const TCHAR.

Edit:

As @David and the other posters have pointed out, you would be better off using Map::value_type& which is a typedef for std::pair<const TCHAR, int>& in this case, because if you later change the types in the map you are using you won't need to change the loop code aswell.

For reference, here is the full error message, where you can see it is trying to convert between two different types of pair, one with TCHAR, the other with 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
    ]


You are not passing an iterator, you're trying to pass a reference to map::value_type. The code as posted should not even compile. Pass map::value_type&, then the program must increment the int value stored in the map.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜