Search code examples
c++vectorboosttransformpush-back

How do I copy the strings in a vector<pair<string, int>> to vector<string>?


I'm using GCC 9.2.0 and boost 1.55.

I have 2 vectors:

vector< pair< string, int > > source;
vector< string > dest;

I need to transform the source vector to the dest, such that it should contain only string elements of source vector.

Is it possible using boost::push_back and adaptors?

boost::range::push_back( dest, source | /* adaptor ??? */ );

Currently I have this workable code, but it should be changed:

transform( source.begin(), source.end(), back_inserter(dest), __gnu_cxx::select1st< std::pair< std::string, int > >() );

Solution

  • To continue the trend of posting mimimal improvements:

    Live On Compiler Explorer

    #include <boost/range/adaptor/map.hpp>
    #include <fmt/ranges.h>
    
    using namespace std::string_literals;
    using namespace boost::adaptors;
    
    template <typename R>
    auto to_vector(R const& range) {
        return std::vector(boost::begin(range), boost::end(range));
    }
    
    int main() {
        std::vector source {std::pair {"one"s,1},{"two",2},{"three",3}};
    
        fmt::print("keys {}\nvalues {}\n",
                source | map_keys,
                source | map_values);
        
        // if you really need the vectors
        auto keys   = to_vector(source | map_keys);
        auto values = to_vector(source | map_values);
    }
    

    Prints

    keys {"one", "two", "three"}
    values {1, 2, 3}