0

std::map から特定の要素をベクターにコピーする必要があります。次のループのように動作するはずです。

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);
    }
}

ファンクターの使用を避けたいが、代わりにboost::lambdaを使用したいので、std::copyを使用してみましたが、うまくいきません。

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

私はラムダ式が初めてで、それらを正しく使用する方法がわかりません。Google でも StackOverflow でも、有用な結果は得られませんでした。 この質問は似ています

4

2 に答える 2

0

STL で必要なのは、transform_if アルゴリズムです。次に、次のように書く必要があります。

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 );

transform_if のコードは、この無関係な質問から取得したもので、次のとおりです。

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; 
}

STL アルゴリズムを使用して両方のステップ (変換と条件付きコピー) を一度に実行する方法は他にないと思います。

于 2010-08-12T18:51:48.633 に答える