typedef std::tuple<A, B, C> TUPLE;
typedef std::vector<TUPLE> TUPLE_VECTOR;
typedef std::vector<A> A_VECTOR;
我想找到从TUPLE_VECTOR创建A_VECTOR的最优雅的方法。
答案 0 :(得分:3)
您可以使用std::transform
从A
中仅复制TUPLE_VECTOR
。看起来像
TUPLE_VECTOR tuples;
A_VECTOR a_vector;
a_vector.reserve(tuples.size());
std::transform(tuples.begin(), tuples.end(), std::back_inserter(a_vector),
[](const auto& tuple){ return std::get<A>(tuple); }); // can also use std::get<0>(tuple)
答案 1 :(得分:0)
以下优点是,它可用于初始化基类/成员对象...
#include <iostream>
#include <boost/iterator/transform_iterator.hpp>
#include <tuple>
#include <vector>
#include <functional>
#include <utility>
typedef std::tuple<int, double> pair;
typedef std::vector<pair> pairVector;
typedef std::vector<int> intVector;
int main()
{ const pairVector sPairs{{0, 1.0}, {2, 3.0}, {4, 5.0}};
typedef boost::transform_iterator<
std::function<const int&(const pair&)>,
pairVector::const_iterator,
const int&,
const int*
> transIt;
const std::function<const int&(const pair&)> sF(
static_cast<const int&(*)(const pair&)>(
std::get<std::size_t(0), int, double>
)
);
const intVector sFirsts(
transIt(
sPairs.begin(),
sF
),
transIt(
sPairs.end(),
sF
)
);
}