我只能在 for 循环内访问向量的元素

I can only access elements of a vector while inside a for loop

我有一个带有通过引用传入的向量的函数。我能够在 for 循环中使用向量将其内容写入文件。但是,如果我尝试在循环外访问向量的任何索引,则会出现此错误:

terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check: __n (which is 10) >= this->size() (which is 0)
Aborted (core dumped)

这是我的代码:

void writeFileVector(vector<string> &wordVector, char *argv[]) {
    ofstream newFileName;
    stringstream ss;

    ss << argv[1];
    string argumentString = ss.str();               // This code is just for creating the name
    ss.str(""); // Clear the stringstream           // of the file
    ss << argumentString << "_vector.txt";          //
    string fileName = ss.str();                     //
    newFileName.open(fileName.c_str());             //

    cout << wordVector.at(0) << endl;               // THIS GIVES ME THE ERROR
    
    for (int i = 0; i < wordVector.size(); i++) {
        cout << wordVector.at(0) << endl;           // This would not give an error, but it also
                                                    // doesn't output anything to the terminal.

        newFileName << wordVector.at(i) << endl;    // This is okay
    }

    newFileName.close();
}

I can only access elements of a vector while inside a for loop

不,您可以在向量范围内的任何地方访问向量的元素。但是您需要确保您访问的是 实际 元素,而不是虚构的元素:-)

关于(稍作修改的)代码:

//cout << wordVector.at(0) << endl;             // THIS GIVES ME THE ERROR
for (int i = 0; i < wordVector.size(); i++) {
    cout << wordVector.at(0) << endl;           // THIS DOESN'T
}

当向量为空时,循环内的cout永远不会执行,因为循环体不会运行。那是因为i < wordVector.size() 开始时 为假,因为 iwordVector.size() 均为零。

如果您要修改循环,使主体 did 运行,您会发现它也在 within 中失败循环:

//cout << wordVector.at(0) << endl;             // THIS GIVES ME THE ERROR
for (int i = -1; i < wordVector.size(); i++) {
    cout << wordVector.at(0) << endl;           // SO DOES THIS
}