首页 文章

C:以深层拷贝更新指针(高效)

提问于
浏览
1

我的问题最好用代码示例说明,所以让我们开始吧:

class Game
{
    // All this vector does is establish ownership over the Card objects
    // It is initialized with data when Game is created and then is never
    // changed.
    vector<shared_ptr<Card> > m_cards;

    // And then we have a bunch of pointers to the Cards.
    // All these pointers point to Cards from m_cards.
    // These could have been weak_ptrs, but at the moment, they aren't
    vector<Card*> m_ptrs;

    // Note: In my application, m_ptrs isn't there, instead there are
    // pointers all over the place (in objects that are stored in member
    // variables of Game.
    // Also, in my application, each Card in m_cards will have a pointer
    // in m_ptrs (or as I said, really just somewhere), while sometimes
    // there is more than one pointer to a Card.
}

现在我想做的是制作这个Game类的深层副本 . 我在其中创建了一个带有新shared_ptrs的新向量,它指向新的Card对象,这些对象是原始Card对象的副本 . 那部分很容易 .

然后麻烦开始了,应该更新m_ptrs的指针以指向m_cards中的卡,这不是一项简单的任务 .

我能想到的唯一方法是创建一个 Map 并在复制m_cards期间填充它(使用 map[oldPtr] = newPtr ),然后使用它来更新m_ptrs . 但是,这只是 O(m * log(n))m = m_ptrs.size(); n = m_cards.size() ) . 因为这将是一个非常常规的操作*我想有效地做到这一点,我觉得它应该可以在 O(m) 使用自定义指针 . 但是,我似乎无法找到一种有效的方法 . 有谁做的?

*它用于为AI创建测试平台,让它“尝试”不同的动作


编辑:我想补充一点接受答案,因为我还没有 . 我等到我回到这个项目之后(因为我在这个项目上做了太多工作,所以我走上了一条小道 - 如果你这么做是为了保持乐趣),所以可能需要一段时间才能接受一个答案 . 不过,我会在一段时间内接受答案,所以不要担心:P


编辑nr 2:我还没有回到这个项目 . 现在,我正在考虑采取 O(m * log(n)) 方式而不是抱怨,然后再看看它是否需要更快 . 但是,由于我最近花了一些时间来学习我的模式,我也认为我真的需要重构一下这个项目 . 哦,我可能只是花了一些时间来处理这个问题,并掌握了我所掌握的所有新知识 . 由于没有't an answer that says 1794840 (and I would actually be pretty disappointed if there was, as it'不是我的问题的答案),我推迟选择一个答案,直到我回到这个项目 .


编辑nr 3:我现在还没有把我的头弯得太过弯曲,如果结果证明这是个问题,那么可能会稍后再看看它 . 然而,这对我的问题来说不是一个好的答案,因为我明确要求提高性能 . 我不想再接受答案,我选择了最有帮助的答案并接受了答案 .

2 回答

  • 3

    将指针存储为索引 . 正如你所说,他们都指向m_Cards,这是一个可以被索引的向量(这是正确的英语?) . 要么这样做只是为了存储,并在加载时将它们转换回指针 . 或者你可能会想到通常使用索引而不是指针 .

  • 0

    如何保持卡元素索引而不是指针:

    vector<int> m_indexes;
    
    ...
    
    Card* ptr = &m_cards[m_indexes[0]];
    

    带索引的矢量可以无需更改即可复制 .

相关问题