我正在使用 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/