C++ 从 list<T> 转换为 vector<T> 的一个 Liner
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5218713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
One Liner to Convert from list<T> to vector<T>
提问by Graviton
Is there an one-liner that converts a list<T>
to vector<T>
?
是否有一个衬垫,其转换list<T>
到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?
谷歌搜索返回了很多使用手动、冗长转换的结果,这让我呕吐。我们是否应该费尽心思去做一些像列表到向量转换这样简单的事情?
回答by Bj?rn Pollex
You can only create a new vector with all the elements from the list:
您只能使用列表中的所有元素创建一个新向量:
std::vector<T> v{ std::begin(l), std::end(l) };
where l
is a std::list<T>
. This will copy all elements from the list to the vector.
哪里l
是std::list<T>
. 这会将列表中的所有元素复制到向量中。
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:
从 C++11 开始,如果您不再需要原始列表,则可以提高效率。您可以将所有元素移动到向量中,而不是复制:
std::vector<T> v{ std::make_move_iterator(std::begin(l)),
std::make_move_iterator(std::end(l)) };
回答by Barry
The accepted answer of:
接受的答案:
std::vector<T> v(std::begin(l), std::end(l));
is certainly correct, but it's (quite unfortunately) not optimal given the recent change in requirement that std::list::size()
be O(1)
. Ifyou have a conforming implementation of std::list
(which, for instance, gcc didn't have until 5+), then the following is quite a bit faster (on the order of 50% once we get to 50+ elements):
肯定是正确的,但鉴于最近的需求变化std::list::size()
是O(1)
. 如果你有一个符合的实现std::list
(例如,gcc 直到 5+ 才有),那么下面的速度会快一些(一旦我们达到 50+ 个元素,速度就会提高 50%):
std::vector<T> v;
v.reserve(l.size());
std::copy(std::begin(l), std::end(l), std::back_inserter(v));
It's not a one liner, but you could always wrap it in one.
它不是单衬,但你总是可以将它包裹在一个中。
回答by Himadri Choudhury
How about this?
这个怎么样?
list<T> li;
vector<T> vi;
copy(li.begin(),li.end(),back_inserter(vi));
回答by Ulrich Beckert
Although this thread is already old, as "append()" is not available anymore, I wanted to show the newer emplace_back one-liner:
虽然这个线程已经很旧了,因为“append()”不再可用,我想展示更新的 emplace_back one-liner:
v.emplace_back(l.begin(), l.end());
But this way every element will be re-constructed, so it may not be the fastest solution!
但是这样每个元素都会被重新构造,所以它可能不是最快的解决方案!