1
    bool takeInt(int a,int b) 
    {
      cout << a << " " << b << endl;   return true;
    } 

    int main()
    { 
      map<int,int> m;
      m.insert(make_pair(1,2));
      m.insert(make_pair(2,5));
      m.insert(make_pair(4,8));
      m.insert(make_pair(5,6));
for_each(m.begin(),m.end(),boost::bind(&takeInt,42,boost::bind(&pair<int,int>::first,_1)));
     return 0;
    }

I want an output of

42 1
42 2
42 4
42 5

Fails compilation with loong errors. Any clue on what I am missing?

1 Answer 1

1

The type of map<T, U>::value_type is pair<const T, U>. Use this:

for_each(m.begin(),m.end(),
         boost::bind(&takeInt, 42, boost::bind(&pair<const int,int>::first,_1)));
                                                     ^^^^^
Sign up to request clarification or add additional context in comments.

4 Comments

out of curiosity: where did find the definition of the map::value_type ? @myself: just looked up definition on cpp.com and it cleary says value_type : 'pair<const Key,T>'
@CarstenGreiner In this case I was pretty sure, otherwise I look it up in the standard (usually the draft N3337 open-std.org/JTC1/SC22/WG21/docs/papers/2012/n3337.pdf) or the library implementation itself.
From this, I learn to always use the typedef unless its not possible. boost::bind(&Map::value_type::first,_1)
@balki Excellent conclusion. Your code also became considerably more robust to change. Essentially, every time you specify template parameters manually to access a nested type, you are making it harder to change your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.