c++ - 如何将 vector<pair<string, int>> 中的字符串复制到 vector<string>?

标签 c++ vector boost transform push-back

我正在使用 GCC 9.2.0 并 boost 1.55。
我有两个 vector :

vector< pair< string, int > > source;
vector< string > dest;
我需要转换 source vector 到 dest ,这样它应该只包含 string source 的元素 vector 。
是否可以使用 boost::push_back和适配器?
boost::range::push_back( dest, source | /* adaptor ??? */ );
目前我有这个可行的代码,但它应该改变:
transform( source.begin(), source.end(), back_inserter(dest), __gnu_cxx::select1st< std::pair< std::string, int > >() );

最佳答案

继续发布最小改进的趋势:
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);
}
打印
keys {"one", "two", "three"}
values {1, 2, 3}

关于c++ - 如何将 vector<pair<string, int>> 中的字符串复制到 vector<string>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65793797/

相关文章:

c++ - 创建全局已知并自动删除的临时目录(C++)?

C++ 为什么迭代器在与 find 函数一起使用时表现不同?

c++ - "thrift -gen cpp"生成的代码无法在 macOS : 'boost/tr1/functional.hpp' file not found 上编译

c++ - C++中的if语句

c++ - 使用关系运算符比较指针是什么意思?

c++ - 为什么 OpenCV KdTree 在 C++ 中总是返回相同的最近邻居?

c++ - 函数 std::make_shared<vector> 的参数太多

c++ - STL Vector是否默认使用 'new'和 'delete'进行内存分配?

C++ boost 图 : how to add_vertex via iteration

c++ - 为什么boost mpl set允许非唯一类型