从列表T转换的一种班轮到向量< T> [英] One liner to convert from list<T> to vector<T>
问题描述
是否存在将 list< T>
转换为 vector< T>
的单线?
Is there an one-liner that converts a list<T>
to vector<T>
?
谷歌搜索返回了很多结果,这些结果需要经过漫长的手动转换,这使我感到恶心.我们应该做这么麻烦的事情来做像列表到矢量的转换那样简单的事情吗?
A google search returns me a lot of results that use manual, lengthy conversion, which make me puke. Should we go to that much trouble to do something as simple as a list-to-vector conversion?
推荐答案
您只能使用列表中的所有元素创建一个新向量:
You can only create a new vector with all the elements from the list:
std::vector<T> v{ std::begin(l), std::end(l) };
其中 l
是 std :: list< T>
.这会将列表中的所有元素复制到向量中.
where l
is a std::list<T>
. This will copy all elements from the list to the vector.
自C ++ 11起,如果您不再需要原始列表,则可以提高效率.无需复制,您可以将所有元素移动到向量中:
Since C++11 this can be made more efficient if you don't need the original list anymore. Instead of copying, you can move all elements into the vector:
std::vector<T> v{ std::make_move_iterator(std::begin(l)),
std::make_move_iterator(std::end(l)) };
这篇关于从列表T转换的一种班轮到向量< T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!