我正在实现一个游戏,并且正在寻找一个合适的容器来模拟一堆纸牌。
强制条件:
- 容器可以随机洗牌(
random iterators
需要,std::list
排除) - 容器可以排序
- 第一个元素可以弹出(从顶部抽一张卡片)
- 可以在末尾插入元素(将卡片丢弃到底部)
到目前为止,我正在使用 std::vector<District>
哪里District
是 enum class
代表卡值。
#include <vector>
#include <algorithm>
namespace Citadel
{
enum class District
{
UNINITIALIZED,
FORTRESS,
MANOR,
// etc
};
class DistrictDeck
{
public:
void Setup(const std::vector<District>& availableDistricts)
{
// Simplified filling...
for (const auto district : availableDistricts)
{
pileOfCards_.push_back(district);
}
// Once all cards have been pushed, shuffle them
std::random_shuffle(std::begin(pileOfCards_), std::end(pileOfCards_));
}
// Pick a district card from top of the stack
District Draw()
{
District district = District::UNINITIALIZED;
if (pileOfCards_.size() > 0)
{
district = pileOfCards_.front();
pileOfCards_.erase(std::begin(pileOfCards_));
}
return district;
}
// Put a district card below the bottom of the stack
void Discard(const District district)
{
pileOfCards_.push_back(district);
}
private:
std::vector<District> pileOfCards_;
};
}
int main()
{
}
哪个容器可以替代std::vector
在我的具体情况下?
最佳答案
vector 可以很好地满足您的目的。使用 Fisher Yates Shuffle 可以最佳地执行洗牌 (O(n)) .
我还应该注意到,基于 std::random_shuffle 的复杂性,这看起来已经是您正在使用的了。
关于c++ - 模拟一堆卡片的最佳容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31929891/