If you want to remove an item from a std::vector
us an use std::vector::erase
, like already used in the code.
(如果要从std::vector
删除项目,请使用std::vector::erase
,就像代码中已经使用的一样。)
That function requires an iterator. (该函数需要一个迭代器。)
Luckely, std::find
, used for finding an element, gives you an iterator. (幸运的是,用于查找元素的std::find
为您提供了迭代器。)
Hence (因此)
P1Hand.erase(std::find(std::cbegin(P1Hand), std::cend(P1Hand), PlayedCardP1));
NB this invalidates iterators and references at or after the point of the erase, including the end()
iterator.
(注意,这将使擦除点或擦除点之后的迭代器和引用无效,包括end()
迭代器。)
So take care it in an iterator loop. (因此,请在迭代器循环中注意这一点。)
See the linked reference page. (请参阅链接的参考页。)
Side note: std::vector
is an array elements in memory.
(旁注: std::vector
是内存中的数组元素。)
If you remove an element in the middle, all items after it will be shifted forward. (如果您删除中间的某个元素,则该元素之后的所有项目都会向前移动。)
That can become inefficient if done very often. (如果经常这样做,可能会导致效率低下。)
An std::list
is more efficient for that, but comes at the cost of more memory interactions when iterating and more storage for link pointers. (一个std::list
对此更有效,但是以迭代时更多的内存交互和链接指针的更多存储为代价。)
You can test which one's better for you. (您可以测试哪个更适合您。)
You could also look at std::unordered_set
, which only can contain each value once. (您还可以查看std::unordered_set
,它只能包含每个值一次。)
But it has other issues. (但这还有其他问题。)
Always test which container works better. (始终测试哪个容器效果更好。)
ps for std::find
you need to #include <algorithm>
(ps for std::find
您需要#include <algorithm>
)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…