You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中如何在运行时创建多个std::array并存储以实现后续更新?

解决多张宾果卡的存储与更新问题

你当前的printCards函数每次循环会覆盖同一个preparedCardArray变量,因此只能保留最后一张卡的状态。要支持多张卡的后续更新,需要用一个容器来存储所有卡的状态,推荐使用std::vector,因为它能动态扩展,适配任意数量的卡。

具体实现步骤

  1. 定义类型别名简化代码
    先给宾果卡的类型起一个别名,让代码更易读:
#include <vector>
#include <array>
#include <iostream>

// 定义宾果卡的类型别名,简化后续代码书写
using BingoCard = std::array<std::array<int, 3>, 9>;
  1. 修改printCards函数存储所有卡
    调整函数逻辑,让它返回一个存储所有卡的std::vector,这样后续可以直接操作这个容器:
// 创建并返回所有宾果卡,同时打印初始状态
std::vector<BingoCard> printCards(int cardCount)
{
    std::vector<BingoCard> allCards; // 用于存储所有卡的容器
    std::array<int, 15> cardArray{};

    std::cout << '\n';

    for (int i = 0; i < cardCount; i++)
    {
        cardArray = createCard();
        cardArray = sortCard(cardArray);
        BingoCard preparedCard = prepareCardsForBingo(cardArray);
        
        allCards.push_back(preparedCard); // 将当前生成的卡加入容器
        cardToConsole(preparedCard);
        std::cout << '\n';
    }

    return allCards;
}
  1. 实现数字抽取后的卡更新逻辑
    编写函数遍历所有卡,标记已抽取的数字,然后刷新控制台显示最新状态:
// 遍历所有卡,标记已抽取的数字
void markNumberOnCards(std::vector<BingoCard>& cards, int drawnNumber)
{
    for (auto& card : cards)
    {
        for (auto& row : card)
        {
            for (int& num : row)
            {
                if (num == drawnNumber)
                {
                    num = 0; // 用0标记已抽取的数字,可替换为你需要的标记(比如-1)
                }
            }
        }
    }
}

// 刷新控制台,显示所有卡的最新状态
void updateConsoleDisplay(const std::vector<BingoCard>& cards)
{
    // Windows环境用cls清屏,Linux/macOS替换为"clear"
    system("cls");
    for (const auto& card : cards)
    {
        cardToConsole(card);
        std::cout << '\n';
    }
}
  1. 主函数中的使用示例
int main()
{
    int cardCount = 3;
    auto allCards = printCards(cardCount);

    // 模拟抽取数字并更新卡状态
    int drawnNum = 15;
    markNumberOnCards(allCards, drawnNum);
    updateConsoleDisplay(allCards);

    return 0;
}

关键点说明

  • 用std::vector存储卡:它支持动态添加元素,完美适配任意cardCount值,且能方便地遍历修改。
  • 引用传递容器:修改卡状态时使用std::vector<BingoCard>&,避免拷贝整个容器,提升性能同时直接修改原数据。
  • 控制台刷新:通过清屏+重新打印所有卡的方式,实现更新后的视觉效果。

内容的提问来源于stack exchange,提问作者rand_program

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 11:55:27