我的问题最好用一个代码示例来说明,所以让我们开始吧:
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 中的卡片,这不是简单的任务。
我能想到的唯一方法是创建一个映射并在复制 m_cards(带有map[oldPtr] = newPtr
)期间填充它,然后使用它来更新 m_ptrs。但是,这只是O(m * log(n))
(m = m_ptrs.size(); n = m_cards.size()
)。因为这将是一个非常常规的操作*我想有效地做到这一点,我觉得O(m)
使用自定义指针应该是可能的。但是,我似乎无法找到一种有效的方法来做到这一点。有谁会吗?
*它用于为人工智能创建一个测试平台,让它“尝试”不同的动作
编辑:我想补充一点关于接受答案,因为我还没有。我一直在等我回到这个项目(因为我在这个项目上工作了太多,所以我走上了旁道——如果你这样做是为了好玩,那就必须保持乐趣),所以在我接受之前可能需要一段时间答案。不过,我会在一段时间内接受答案,所以不要担心:P
编辑 nr 2:我还没有回到这个项目。现在,我正在考虑只是采取O(m * log(n))
方式而不是抱怨,然后看看是否需要更快。然而,由于我最近花了一些时间来学习我的模式,我也认为我真的需要一些时间来重构这个项目。哦,我可能会花一些时间利用我掌握的所有新知识来解决这个问题。由于没有答案说“只需坚持使用哈希图,稍后再看看它是否真的需要更快”(如果有的话,我实际上会非常失望,因为这不是我问题的答案),我是推迟选择答案,直到我回到这个项目。
编辑 nr 3:我仍然没有回到这个项目。更准确地说,它已被无限期搁置。我很确定我现在不会让我的头太低O(m * log(n))
,然后如果结果证明是个问题,也许以后再看看。但是,这并不是我的问题的好答案,因为我明确要求更好的性能。不想让答案不再被接受,我选择了最有帮助的答案并接受了它。