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

C++队列操作后返回字符串出现垃圾值问题求助

问题排查与修正

核心错误点

  • 返回类型不匹配:函数CommunityChest声明返回单个string,但实际需要返回字符串数组,这是根本逻辑错误。而且栈上的局部数组(比如newQ1)在函数结束后会被销毁,返回其元素或指针必然导致垃圾值。
  • 数组复制越界:newQ1是长度为5的数组,但你用i从ComQ.front(此时为1)开始赋值,会写到newQ1[5],超出数组索引范围(0-4),触发内存错误。
  • 错误的返回逻辑:循环内的return newQ1[i];会在第一次循环就返回单个元素,后续复制逻辑完全不执行。
  • main函数接收错误:用单个string变量接收返回值,遍历它的索引实际是访问字符串的单个字符,自然输出垃圾内容。

修正方案

改用C++标准库的vector<string>替代原生数组,它能安全传递和返回,同时保留你手动实现队列的逻辑。

修正后的代码

#include<iostream>
#include<string>
#include<vector>
using namespace std;

vector<string> CommunityChest(vector<string> Cards){
    struct Que{
        string cards[6];
        int front = 0;
        int back = -1;
    } ComQ;
    string temp;

    // 入队原始卡牌
    for(int i = 0; i < Cards.size(); i++){
        ComQ.back++;
        if(ComQ.back <= 5){
            ComQ.cards[ComQ.back] = Cards[i];
        } else {
            cout << "Overflow" << endl;
            return {}; // 出错返回空容器
        }
    }

    // 显示初始队列(可选)
    cout << "初始队列:" << endl;
    for(int i = ComQ.front; i <= ComQ.back; i++){
        cout << ComQ.cards[i] << endl;
    }

    // 取出队首元素
    if(ComQ.front <= ComQ.back){ // 正确判断队列非空
        temp = ComQ.cards[ComQ.front];
        ComQ.front++;
    } else {
        cout << "队列空" << endl;
        return {};
    }
    cout << "\n取出顶部卡牌:" << endl;
    cout << temp << endl;

    // 将取出的卡牌放回队尾
    ComQ.back++;
    if(ComQ.back <= 5){
        ComQ.cards[ComQ.back] = temp;
    } else {
        cout << "Overflow" << endl;
        return {};
    }

    // 整理并返回更新后的卡牌数组
    vector<string> newQ;
    for(int i = ComQ.front; i <= ComQ.back; i++){
        newQ.push_back(ComQ.cards[i]);
    }

    cout << "\n将顶部卡牌移至末尾后的队列:" << endl;
    for(const auto& s : newQ){
        cout << s << endl;
    }

    return newQ;
}

int main(){
    vector<string> cards = {
        "1 Advance ........",
        "2. It is your ...........",
        "3. You have won .............",
        "4. From sale of..............",
        "5. Pay Hospital............"
    };

    vector<string> newQ = CommunityChest(cards);

    cout << "\nmain函数中接收的更新后卡牌:" << endl;
    for(int i = 0; i < newQ.size(); i++){
        cout << newQ[i] << endl;
    }

    return 0;
}

关键修正说明

  1. 用vector传递数据:避免原生数组的内存管理问题,支持安全的赋值和返回。
  2. 修复队列边界检查:用ComQ.front <= ComQ.back判断队列非空,逻辑更准确。
  3. 正确复制队列元素:从队首开始遍历,将元素逐个存入vector,避免数组越界。
  4. main函数正确接收:用vector<string>接收返回值,遍历容器输出完整的卡牌内容。

内容的提问来源于stack exchange,提问作者Abdurrehman Afzal Warraich

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:05:26