c++ - 模拟一堆卡片的最佳容器

标签 c++ algorithm c++11 optimization stl

我正在实现一个游戏,并且正在寻找一个合适的容器来模拟一堆纸牌。

强制条件:

  1. 容器可以随机洗牌(random iterators需要,std::list排除)
  2. 容器可以排序
  3. 第一个元素可以弹出(从顶部抽一张卡片)
  4. 可以在末尾插入元素(将卡片丢弃到底部)

到目前为止,我正在使用 std::vector<District>哪里Districtenum class代表卡值。

Live demo

#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/

相关文章:

c++ - 在visual studio 2010下编译64位

arrays - 两个元素之间的最大差等于求解最大子数组?

algorithm - 我应该使用什么算法来查看是否可以从给定数字中得到 n

c - 如何使用ZeroMQ实现多个套接字?

c++ - 从 C 创建 C++ 类,我可以将 C++ 对象传递给 C 中的 C++ 构造函数吗?

c++ - 添加字符串的空结尾

algorithm - Trie 实现 - 将元素插入到 trie 中

c++ - XCode 4.5 'tr1/type_traits' 找不到文件

c++ - 工厂能否通过查看特定文件以某种方式确定所有可能的类?

c++ - 通过重复的操作序列简化 GTest 用例