正如评论中提到的克里斯,最简单的解决方案是使用std::transform
std::transform( songs.begin(), songs.end(),
std::ostream_iterator<int>( std::cout, "\n" ),
[]( decltype(v)::value_type const& p ) -> decltype(p.first) {
return p.first;
}
);
如果您想使用自定义迭代器路线,请创建一个模仿ostream_iterator
的行为的类型,并另外用于std::get
仅检索您关心的项目。
template<std::size_t N>
struct get_tuple_item_iterator
: public std::iterator<std::output_iterator_tag, void, void, void, void>
{
get_tuple_item_iterator( std::ostream& os, std::string term )
: os_(os)
, term_(std::move(term))
{}
template<typename... T>
get_tuple_item_iterator& operator=( std::tuple<T...> const& elem )
{
static_assert(N < sizeof...(T), "N is out of range");
os_ << std::get<N>( elem ) << term_;
return *this;
}
template<typename T1, typename T2>
get_tuple_item_iterator& operator=( std::pair<T1, T2> const& elem )
{
static_assert((N == 0) || (N == 1), "N must be 0 or 1 for std::pair");
return operator=( std::tie( elem.first, elem.second ) );
}
get_tuple_item_iterator& operator*() { return *this; }
get_tuple_item_iterator& operator++() { return *this; }
get_tuple_item_iterator& operator++( int ) { return *this; }
private:
std::ostream& os_;
std::string term_;
};
用它作为
std::copy( songs.begin(), songs.end(),
get_tuple_item_iterator<0>( std::cout, "\n" ) );