views:

36

answers:

1

I have to copy certain elements from a std::map into a vector. It should work like in this loop:

typedef int First;
typedef void* Second;
std::map<First, Second> map;
// fill map
std::vector<Second> mVec;
for (std::map<First, Second>::const_iterator it = map.begin(); it != map.end(); ++it) {
    if (it->first % 2 == 0) {
        mVec.push_back (it->second);
    }
}

Since I'd like to avoid using any functors, but use boost::lambda instead, I tried using std::copy, but can't get it right.

std::copy (map.begin(), map.end(), std::back_inserter(mVec)
                bind(&std::map<int, void*>::value_type::first, _1) % 2 == 0);

I'm new to lambda expressions, and I can't figure it out how to use them correctly. I didn't get any useful results on Google or StackOverflow either. This question is similar

A: 

What you would need in STL would be a transform_if algorithm. Then you would have to write:

transform_if (mymap.begin(), mymap.end(), 
     back_inserter(myvec),  
     bind(&std::map<First, Second>::value_type::second, _1) ,
     (bind(&std::map<First, Second>::value_type::first, _1) % 2) == 0 );

The code for transform_if is taken from this unrelated question and it is:

template<class InputIterator, class OutputIterator, class UnaryFunction, class Predicate>
OutputIterator transform_if(InputIterator first, 
                            InputIterator last, 
                            OutputIterator result, 
                            UnaryFunction f, 
                            Predicate pred)
{
  for (; first != last; ++first)
  {
    if( pred(*first) )
      *result++ = f(*first);
  }
  return result; 
}

I think there is no other way to perform both steps (transform and conditional copy) at once using STL algorithms.

vladmihaisima