迭代一个可变容器

9
我正在遍历一组回调函数。在迭代过程中调用这些函数可能会导致对函数集合的实际容器进行重大更改。
我现在做的是:
1. 复制原始集合 2. 遍历副本,但对于每个元素都检查它是否仍然存在于原始集合中
检查每个元素的存在性非常动态,但似乎也相当慢。
有其他提议来解决这种情况吗?
编辑:这是实际代码:
    // => i = event id
    template <class Param>
    void dispatchEvent(int i, Param param) {

        EventReceiverSet processingNow;

        const EventReceiverSet& eventReceiverSet = eventReceiverSets[i];
        std::copy(eventReceiverSet.begin(), eventReceiverSet.end(), std::inserter(processingNow, processingNow.begin()));

        while (!processingNow.empty()) {
            EventReceiverSet::iterator it = processingNow.begin();
            IFunction<>* function = it->getIFunction(); /// get function before removing iterator
            processingNow.erase(it);

            // is EventReceiver still valid? (may have been removed from original set)
            if (eventReceiverSet.find(ERWrapper(function)) == eventReceiverSet.end()) continue; // not found

            function->call(param);
        }
    };

你所说的“set”是指std::set<>吗?如果不是,那么实际的容器类型是什么? - ildjarn
好的,我本想让它通用一些,但是没错,它是一个std::set。 - Bill Kotsias
3个回答

4
两种基本方法如下:
  1. 采用任务驱动的方法(在锁定集合的情况下,为每个元素推送任务到队列中,然后释放所有方面进行工作并等待完成)。当任务实际开始时,仍需要检查当前任务的元素是否仍然存在于集合中。

    • 这可以利用读写锁进行检查,这通常比完全互斥更快(特别是读者多于写者)

  2. 使用并发数据结构(我的意思是适用于多线程访问而无需显式锁定的数据结构)。以下库包含并发数据结构的实现:

(链接即将添加)

3

有一种方法可以分为两个步骤:首先,浏览原始数据集,并创建一个操作项集合。然后,浏览操作项集合,并将其应用于原始数据集。

操作项是一个基类及其子类。每个子类接收一个数据集并对其执行特定的操作,例如:

struct set_action {
    virtual void act(std::set<int> mySet) const;
};
class del_action : public set_action {
private:
    int item;
public:
    del_action(int _item) : item(_item) {}
    virtual void act(std::set<int> mySet) const {
        // delete item from set
    }
};
class upd_action : public set_action {
private:
    int from, to;
public:
    upd_action(int _from, int _to) : from(_from), to(_to) {}
    virtual void act(std::set<int> mySet) const {
        // delete [from], insert [to]
    }
};

现在您可以在第一次执行中创建set_action*的集合,并在第二次执行中运行它们。


3

你引用的链接中写道:void set::erase ( iterator position ); - Bill Kotsias

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接