追加到一个向量,而迭代它? [英] Appending to a vector while iterating over it?

查看:136
本文介绍了追加到一个向量,而迭代它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向量,我正在迭代。在迭代时,我可以向向量添加新值。它看起来像:

I have a vector that I am iterating over. While iterating, I may append new values to the vector. It looks something like:

struct Foo
{
   bool condition;
};

void AppendToVec(vector<Foo>& v)
{
   ...
   v.push_back(...);
}

vector<Foo> vec;
...
for (vector<Foo>::size_type i = 0; i < vec.size(); ++i)
{
   if (vec[i].condition) AppendToVec(vec);
}

这很好,事实上,递归地需要添加更多的元素,但它感觉有点脆弱。如果有人来,调整循环,它很容易被打破。例如:

This works fine, and in fact elegantly handles the case where the newly appended elements recursively require even more elements to be added, but it feels a little fragile. If someone else comes along and tweaks the loop, it can easily be broken. For example:

//No longer iterates over newly appended elements
vector<Foo>::size_type size = vec.size();
for (vector<Foo>::size_type i = 0; i < size; ++i)
{
   if (vec[i].condition) AppendToVec(vec);
}

//Vector resize may invalidate iterators
for (vector<Foo>::iterator i = vec.begin(); i != vec.end(); ++i)
{
   if (vec->condition) AppendToVec(vec);
}

有没有任何最佳实践来处理这种情况?用警告:这个循环是有意地在迭代时附加到向量来注释循环,谨慎地改变最好的方法?

Are there any best practices to handle cases like this? Is commenting the loop with a "Warning: This loop is intentionally appends to the vector while iterating. Change cautiously" the best approach? I am open to switching containers too if that makes things more robust.

推荐答案

我对这个问题的解决方法往往是创建一个队列我添加任何新的元素,然后迭代原始容器后,处理队列中的元素和/或将它们附加到原始。

My approach to this problem is often to create a queue to which I add any new elements, and then after iterating over the original container, process the elements in the queue and/or append them to the original.

这种方法是明显的,它的工作原理在多线程可以入队新元素的情况下。

The good points to this approach are that what is going on is obvious, and it works in scenarios where multiple threads could be enqueuing new elements.

这篇关于追加到一个向量,而迭代它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆