1

I'd like to ask you how could I copy all second elements from

map<string, string> myMap

to

deque<string> myDeq

using for_each or transform without creating a functor. I tried it like in this question

transform(myMap.begin(), myMap.end(), back_inserter(myDeq), mem_fun_ref(&map<string, string>::value_type::second)); 

but it didn't work for me - I got error "Illegal use of this type".

Community
  • 1
  • 1
DropDropped
  • 1,253
  • 1
  • 22
  • 50

1 Answers1

0

The reason you get the error is because map<string, string>::value_type::second is not a member function. It is just a member variable of the std::pair template struct.

One possible solution without using functors is with the use of lambdas. But it's a C++11 feature so I don't know if that's what you want.

Take a look at the following example

#include <iostream>
#include <map>
#include <deque>
#include <algorithm>
#include <string>
#include <iterator>

using namespace std;

int main()
{
    map<string,string> myMap;
    deque<string> myDeque;

    myMap["key1"]="value1";
    myMap["key2"]="value2";
    transform(myMap.begin(),myMap.end(),back_inserter(myDeque),[](map<string,string>::value_type p){return p.second;});

    copy(myDeque.begin(),myDeque.end(),ostream_iterator<string>(cout,"\n"));
}