【问题标题】:Trying to get to grips with C++ and cant work out why this doesn't print out the names of the vector<string> entries试图掌握 C++ 并且无法弄清楚为什么这不会打印出 vector<string> 条目的名称
【发布时间】:2025-12-07 15:35:02
【问题描述】:

所以这段代码不会打印出矢量游戏库中的条目

最初我只是使用 gameLibrary.pushback(" ") 函数来添加它们并且效果很好。

我只是想弄清楚为什么这不起作用。当(至少在我看来它正在做同样的事情)

#include <iostream>
#include <vector>
#include <string>

using std::cout;
using std::vector;
using std::string;

void addGame(vector<string> gameLibrary, string gameName);

int main()
{
    vector<string> gameLibrary;
    vector<string>::iterator editIter;
    
    addGame(gameLibrary, "game");
    addGame(gameLibrary, "game 2");

    cout << "Your library: " << std::endl;

    for (editIter = gameLibrary.begin(); editIter != gameLibrary.end(); ++editIter)
    {
        cout << *editIter << std::endl;
    }
    
    return 0;
}


void addGame(vector<string>gameLibrary, string gameName)
{
    gameLibrary.emplace_back(gameName);
}

【问题讨论】:

    标签: c++ vector iterator


    【解决方案1】:

    addGame 不能接收它通过复制填充的向量。它必须通过引用或指针传递。

    引用传递示例:

    void addGame(vector<string>& gameLibrary, string gameName)
    {
        gameLibrary.emplace_back(gameName);
    }
    

    否则,副本被修改,所以main中声明的向量不变。

    【讨论】:

    • 感谢您的回复,现在这完全有道理了!
    【解决方案2】:

    请阅读按值传递与引用传递。在您的函数中,您通过值传递数组,这意味着只有数组的值被复制到函数中。

    对函数内部数组的任何更改都不会反映回来。如果你需要,你需要通过引用传递你的数组

    看到这个答案:Are vectors passed to functions by value or by reference in C++

    【讨论】:

    • 啊,我明白了,知道这真的很有用。感谢您的回复!
    最近更新 更多