C++ std::transform vector of pairs->first to new vector

前端 未结 6 2124
你的背包
你的背包 2020-12-31 00:51

Sorry for a little bit beginner question. There are vector and vector of pairs

typedef std::vector  TItems;
typedef std::vector < std::pair <         


        
6条回答
  •  长情又很酷
    2020-12-31 01:32

    First of all, you should use a back_inserter as the third argument to transform so that the transformed values are pushed to the back of the vector.

    Second, you need some sort of functor which takes a pair of ints and returns the first one. This should do:

    int firstElement( const std::pair &p ) {
        return p.first;
    }
    

    Now, to put the pieces together:

    TPairs pairs;
    pairs.push_back( std::make_pair( 1, 3 ) );
    pairs.push_back( std::make_pair( 5, 7 ) );
    
    TItems items;
    std::transform( pairs.begin(), pairs.end(), std::back_inserter( items ),
                    firstElement );
    

    After this code, items contains 1 and 5.

提交回复
热议问题