所以我试图编写一个更改数组之外的函数,就像将值传递给函数作为引用一样。 这是我的代码:
std::array<Card, 52> deck {};
std::array<Card, 52> &deckRef = deck;
initializeDeck(deckRef);
printDeck(deckRef);
和
void initializeDeck(std::array<Card, 52> deck){
int16_t cardNumber{0};
for(int counterSuit{0}; counterSuit < CardSuit::MAX_SUITS; ++counterSuit)
{
for(int counterRank{0}; counterRank < CardRank::MAX_RANKS; ++counterRank)
{
Card card { static_cast<CardRank::CardRank>(counterRank),
static_cast<CardSuit::CardSuit>(counterSuit)};
deck[cardNumber] = card;
++cardNumber;
}
}}
void printDeck(std::array<Card, 52> deck){
for(int16_t counter{0}; counter < 52; ++counter)
{
printCard(deck[counter]);
}}
printDeck打印垃圾但是如果我将printCard()添加到initializeDeck(),它会打印所有卡片,但它不会存储在main()中的原始数组中。
我这样做时会收到此错误;
void initializeDeck(std::array<Card, 52>& deck)
undefined reference to `initializeDeck(std::array<Card, 52u>)'|
提前致谢! 提前谢谢!
答案 0 :(得分:4)
您需要将deck作为参考传递,以便函数外部具有更改。即代码应为
void initializeDeck(std::array<Card, 52>& deck){
答案 1 :(得分:0)
主题的轻微扩展,但如果您愿意,可以在编译时生成套牌:(此示例需要c ++ 14,但c ++ 11可以通过更多工作来完成)
#include <iostream>
#include <iterator>
#include <algorithm>
#include <array>
enum class Suit { Spades, Diamonds, Clubs, Hearts };
std::ostream& operator<<(std::ostream& os, Suit s) {
switch (s) {
case Suit::Spades: return os << "spades";
case Suit::Diamonds: return os << "diamonds";
case Suit::Clubs: return os << "clubs";
case Suit::Hearts: return os << "hearts";
}
}
enum class Rank { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace };
std::ostream& operator<<(std::ostream& os, Rank r) {
switch (r) {
case Rank::Two: return os << "two";
case Rank::Three: return os << "three";
case Rank::Four: return os << "four";
case Rank::Five: return os << "five";
case Rank::Six: return os << "six";
case Rank::Seven: return os << "seven";
case Rank::Eight: return os << "eight";
case Rank::Nine: return os << "nine";
case Rank::Ten: return os << "ten";
case Rank::Jack: return os << "jack";
case Rank::Queen: return os << "queen";
case Rank::King: return os << "king";
case Rank::Ace: return os << "ace";
}
}
struct Card {
Suit suit;
Rank rank;
};
std::ostream& operator<<(std::ostream& os, const Card& c) {
return os << c.rank << " of " << c.suit;
}
constexpr Card make_card(size_t index)
{
return Card {
static_cast<Suit>(index / 13),
static_cast<Rank>(index % 13)
};
}
using Deck = std::array<Card, 52>;
template<size_t...Is>
constexpr Deck generate_deck_impl(std::index_sequence<Is...>)
{
return { make_card(Is)... };
}
constexpr Deck generate_deck()
{
return generate_deck_impl(std::make_index_sequence<52>());
}
int main()
{
using namespace std;
auto deck = generate_deck();
std::copy(begin(deck), end(deck), ostream_iterator<Card>(cout, ", "));
cout << endl;
random_shuffle(begin(deck), end(deck));
std::copy(begin(deck), end(deck), ostream_iterator<Card>(cout, ", "));
cout << endl;
}