矢量初始化而不使用默认构造函数

时间:2011-05-16 01:29:21

标签: c++

如何在没有默认构造函数的情况下减少以下代码行数?

#include <vector>

enum Rank { DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE };

enum Suit { HEART, DIAMOND, CLUB, SPADE };

struct Card {
    Card(Rank r, Suit s) : rank(r), suit(s) { }
    Card(const Card& copy) : rank(copy.rank), suit(copy.suit) {}

    Rank rank;
    Suit suit;
};

const Card deckOfCards[52] = {
    Card(ACE, HEART),
    Card(DEUCE, HEART),
    Card(THREE, HEART),
    Card(FOUR, HEART),
    Card(FIVE, HEART),
    Card(SIX, HEART),
    Card(SEVEN, HEART),
    Card(EIGHT, HEART),
    Card(NINE, HEART),
    Card(TEN, HEART),
    Card(JACK, HEART),
    Card(QUEEN, HEART),
    Card(KING, HEART),
    Card(ACE, DIAMOND),
    Card(DEUCE, DIAMOND),
    Card(THREE, DIAMOND),
    Card(FOUR, DIAMOND),
    Card(FIVE, DIAMOND),
    Card(SIX, DIAMOND),
    Card(SEVEN, DIAMOND),
    Card(EIGHT, DIAMOND),
    Card(NINE, DIAMOND),
    Card(TEN, DIAMOND),
    Card(JACK, DIAMOND),
    Card(QUEEN, DIAMOND),
    Card(KING, DIAMOND),
    Card(ACE, CLUB),
    Card(DEUCE, CLUB),
    Card(THREE, CLUB),
    Card(FOUR, CLUB),
    Card(FIVE, CLUB),
    Card(SIX, CLUB),
    Card(SEVEN, CLUB),
    Card(EIGHT, CLUB),
    Card(NINE, CLUB),
    Card(TEN, CLUB),
    Card(JACK, CLUB),
    Card(QUEEN, CLUB),
    Card(KING, CLUB),
    Card(ACE, SPADE),
    Card(DEUCE, SPADE),
    Card(THREE, SPADE),
    Card(FOUR, SPADE),
    Card(FIVE, SPADE),
    Card(SIX, SPADE),
    Card(SEVEN, SPADE),
    Card(EIGHT, SPADE),
    Card(NINE, SPADE),
    Card(TEN, SPADE),
    Card(JACK, SPADE),
    Card(QUEEN, SPADE),
    Card(KING, SPADE)
};

class Deck {
public:
    Deck() : cards(deckOfCards, deckOfCards + 52) {}
    ~Deck() {}

private:
    std::vector<Card> cards;
};

1 个答案:

答案 0 :(得分:5)

您可以使用循环并将元素添加到构造函数体中的容器中:

Deck() 
{
    for (int rank = (int)DEUCE; rank <= (int)ACE; ++rank) 
    {
        for (int suit = (int)HEART; suit <= (int)SPADE; ++suit)
        {
            cards.push_back(Card((Rank)rank, (Suit)suit));
        }
    }
}

如果每个枚举都有FIRST_ENUMERATORLAST_ENUMERATOR的标记,这可以变得更干净,更不容易出错,但即使没有这个,这仍然比手工输入所有组合更好。