Why does std :: map behave strangely when passing a value to lambda?

I have been using C ++ 0x for a while and really enjoy the new functions of the lamba function. I'm used to specifying [=] in my lambda declarations to indicate that I want to pass variables with an external border to my lambda by value.

However, today I ran into a very strange lambda problem. I noticed that passing a map with an external border to lamba by value while working for_each is weird. Here is an example that shows the problem:

void LambdaOddnessOne ()
{
    map<int, wstring> str2int;
    str2int.insert(make_pair(1, L"one"));
    str2int.insert(make_pair(2, L"two"));

    vector<int> numbers;
    numbers.push_back(1);
    numbers.push_back(2);

    for_each ( numbers.begin(), numbers.end(), [=]( int num ) 
    {
        //Calling find() compiles and runs just fine
        if (str2int.find(num) != str2int.end())
        {
            //This won't compile... although it will outside the lambda
            str2int[num] = L"three";

            //Neither will this saying "4 overloads have no legal conversion for 'this' pointer"
            str2int.insert(make_pair(3, L"three"));
        }
    });

}

Many of the map methods can be called from within lamba (for example, find), but many other methods led to compilation errors when they compiled just fine outside of lamba.

An attempt to use the operator [for example, resulted in:

error C2678: binary '[' : no operator found which takes a left-hand operand of type 'const std::map<_Kty,_Ty>' (or there is no acceptable conversion)

An attempt to use the .insert function resulted in the following:

error C2663: 'std::_Tree<_Traits>::insert' : 4 overloads have no legal conversion for 'this' pointer

- ? MS? .

+3
2

- const ( , ), , mutable:

for_each ( numbers.begin(), numbers.end(), [=]( int num ) mutable
{
    // ...

. ++ 0x "" ?

+4

All Articles