how copy the first elements of pair in vector to another vector?

前端 未结 2 1007
时光取名叫无心
时光取名叫无心 2021-01-25 13:49

I have a std::vector with element of the type std::pair. With some algorithm, I return two iterators (range) so I would like to pick up all elements within that range and copy t

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-25 13:56

    If you are after an algorithm to do this for you, you can use the four parameter overload of std::transform:

    #include  // for transform
    #include   // for back_inserted and distance
    
    ....
    std::vector< pair > data;
    std::vector data2;
    data2.reserve(std::distance(it1, it2));
    std::transform(it1, 
                   it2, 
                   std::back_inserter(data2), 
                   [](const std::pair& p){return p.first;});
    

    If you don't have C++11 support, you can use a function instead of the lambda expression:

    double foo(const std::pair& p) { return p.first; }
    
    std::transform(it1, 
                   it2, 
                   std::back_inserter(data2),
                   foo);
    

提交回复
热议问题