开发者

Copy map to vector

开发者 https://www.devze.com 2023-01-10 01:58 出处:网络
I have 开发者_开发问答to copy certain elements from a std::map into a vector. It should work like in this loop:

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


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.


You can use boost range adaptors to achieve that.

using namespace boost::adaptors;

boost::copy( map | filtered( [] (const pair<First,Second> &p)->bool {return p.first % 2 == 0;})
                 | transformed( [] (const pair<First,Second> &p) {return p.second;}),
             std::back_inserter(mVec));
0

精彩评论

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