将向量复制到 STL 列表的最佳方法?

发布于 2024-07-11 09:45:15 字数 40 浏览 4 评论 0原文

使用迭代器迭代向量并复制到列表是最佳的复制方法。 有什么建议吗?

Is iterating through the vector using an iterator and copying to a list the most optimal method of copying. Any recommendations?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

不再让梦枯萎 2024-07-18 09:45:15

为什么要迭代而不使用标准复制算法?

std::copy( vector.begin(), vector.end(), std::back_inserter( list ) );

由于 C++20 std::ranges::copy 使其变得更加容易

std::ranges::copy(vector, std::back_inserter( list ) );

Why would you iterate and not use the standard copy algorithm?

std::copy( vector.begin(), vector.end(), std::back_inserter( list ) );

Since C++20 std::ranges::copy makes it even easier

std::ranges::copy(vector, std::back_inserter( list ) );
百思不得你姐 2024-07-18 09:45:15

如果您要创建一个新列表,则可以利用采用开始和结束迭代器的构造函数:

std::list<SomeType> myList(v.begin(), v.end());

如果您有要附加到的现有列表,Kasprzol 的答案是完美的。

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.

一个人的旅程 2024-07-18 09:45:15
list.assign(vector.begin(), vector.end());
list.assign(vector.begin(), vector.end());
二智少女 2024-07-18 09:45:15

我喜欢这个构建新列表的建议。

std::list<SomeType> myList(v.begin(), v.end());

但是,当附加到现有列表时,以下内容可能对于小数据集是最佳的。 我所说的“最佳”是指最容易记住如何做并且最容易理解。 (这些都是主观陈述,我确信这取决于您的大脑如何连接。)

for ( unsigned i=0; i<v.size(); i++ ) myList.push_back(v[i]);

在许多情况下,在向量上使用迭代器可能过于迂腐。 简单的索引通常效果很好。

另一个线程讨论了迭代器与索引(此处)。 在该线程中,所采取的答案基本上首选迭代器,因为它们更通用。 但如果向量是最常用的容器类型,我认为专门化这种简单的算法是合理的。

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.

凌乱心跳 2024-07-18 09:45:15

您可以尝试使用 标头中的更棘手的东西,例如 for_eachcopy ...但它们相当于在我看来,同样的事情。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文