C++ 将向量复制到 STL 列表的最佳方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/458476/
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
Best way to copy a vector to a list in STL?
提问by kal
Is iterating through the vector using an iterator and copying to a list the most optimal method of copying. Any recommendations?
是使用迭代器遍历向量并将复制到列表中的最佳复制方法。有什么建议吗?
回答by Kasprzol
Why would you iterate and not use the standard copy algorithm?
为什么要迭代而不使用标准的复制算法?
std::copy( vector.begin(), vector.end(), std::back_inserter( list ) );
回答by Fred Larson
If you're making a new list, you can take advantage of a constructor that takes begin and end iterators:
如果您正在创建一个新列表,您可以利用带有开始和结束迭代器的构造函数:
std::list<SomeType> myList(v.begin(), v.end());
Kasprzol's answer is perfect if you have an existing list you want to append to.
如果您有要附加到的现有列表,Kasprzol 的答案是完美的。
回答by Dennis
list.assign(vector.begin(), vector.end());
回答by Dennis
I like this suggestion for constructing a new list.
我喜欢这个构建新列表的建议。
std::list<SomeType> myList(v.begin(), v.end());
But when appending to an existing list, the following may be optimal for small data sets. By "optimal", I mean that it is easiest to remember how to do and easiest to understand. (These are subjective statements, I'm sure it depends on how your brain is wired.)
但是当附加到现有列表时,以下可能是小数据集的最佳选择。我所说的“最佳”是指最容易记住怎么做,也最容易理解。(这些都是主观陈述,我敢肯定这取决于你的大脑是如何连接的。)
for ( unsigned i=0; i<v.size(); i++ ) myList.push_back(v[i]);
Using iterators on vectors may be overly pedantic in many cases. Simple indexing usually works fine.
在许多情况下,在向量上使用迭代器可能过于迂腐。简单的索引通常工作正常。
Another thread addresses iterators vs. indices (here). In that thread, the taken answer basically preferred iterators because they are more generic. But if vectors are the most commonly used container type, I think it is reasonable to specialize this kind of simple algorithm.
另一个线程处理迭代器与索引(此处)。在该线程中,采用的答案基本上首选迭代器,因为它们更通用。但是如果向量是最常用的容器类型,我认为将这种简单算法专门化是合理的。
回答by ChrisW
You can try to use trickier things from the <algorithm>
header, for example for_each
or copy
... but they would amount to the same thing, in my opinion.
例如,您可以尝试从<algorithm>
标题中使用更棘手的东西,for_each
或者copy
……但在我看来,它们的效果是一样的。