简体   繁体   English

实现《战地风云3》的std :: vector交换技巧以“删除/添加”元素

[英]Implementing Battlefield 3's std::vector swap trick to “remove/add” an element

I'm trying to implement an algorithm and I stumbled upon DICE's "swap trick" as described here (slide 19). 我想实现一个算法,我偶然发现了描述DICE的“交换技巧” 这里 (幻灯片19)。

From what I understand, we first create a vector with all of our elements and then when an element needs to be deleted, it is swapped with the last one and we decrease the "size" of the vector. 据我了解,我们首先创建一个包含所有元素的向量,然后在需要删除某个元素时,将其与最后一个元素交换,然后减小向量的“大小”。 This "size" is an external variable to keep track of our "virtual" size (because a vector doesn't support this internally ). 此“大小”是一个外部变量,用于跟踪我们的“虚拟”大小(因为矢量内部不支持此大小)。

NOTE: ordering/sorting is not important. 注意:排序/排序并不重要。 Also, when I say "delete", nothing is de-allocated, it's just saying that the element is moved outside of the "usable" range. 另外,当我说“删除”时,没有任何东西被取消分配,这只是说元素移到了“可用”范围之外。

Now, when the moment comes to add an element (from the deleted ones) back in the usable part of the vector, we need to swap it back somewhere. 现在,当需要将元素(来自已删除元素)添加回向量的可用部分时,我们需要将其交换回某个位置。 And this is where I'm blocking a bit. 这就是我要阻止的地方。 Because, when we swap it, we could be swapping it with an element that needs to be there at this iteration and this same element would need to be swapped back and so on... 因为,当我们交换它时,我们可以将它与需要在此迭代中存在的元素交换,并且该相同的元素将需要交换回来,依此类推...

This is an example how it should work : 这是一个示例,它应如何工作:

iteration 1 : |1 2 3 4| 迭代1:| 1 2 3 4 | (size 4) (尺寸4)

iteration 2 : |1 3| 迭代2:| 1 3 | 2 4 (size 2 with the elements '2' and '4' still there in memory but not accounted for in the size of the vector) 2 4(大小2,元素'2'和'4'仍然存在于内存中,但未考虑向量的大小)

iteration 3 : |2 1 3| 迭代3:| 2 1 3 | 4 (size 3 with the element '4' still there) 4(大小为3,元素“ 4”仍然存在)

I might be over-thinking it, but if anyone has an idea of how to get this algorithm right, that would be helpful. 我可能想得太过分了,但是如果有人对如何正确实现此算法有所了解,那将会有所帮助。

Thanks for any help. 谢谢你的帮助。

Swap it with the first unusable element, then increment your virtual size. 将其与第一个不可用的元素交换,然后增加虚拟大小。 So, for example, let's say this is your vector: 例如,假设这是您的向量:

  // usable         unusable
{ 0, 1, 2, 3,       4, 5, 6, 7, 8 } // virtual size = 4

Now let's say you want to move the 7 from the unusable portion to the usable portion. 现在,假设您要将7从不可用的部分移到可用的部分。 You swap it with the 4, since that's the first unusable element. 您将其交换为4,因为这是第一个不可用的元素。 And then you increment your virtual size by 1. So now your vector looks like this: 然后,您将虚拟大小增加1。因此,向量如下所示:

  // usable         // unusable
{ 0, 1, 2, 3, 7,    5, 6, 4, 8 } // virtual size = 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM