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

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

本文关键字:访问 向量 元素 循环 for      更新时间:2024-09-23

我有一个函数,它有一个通过引用传递的向量。我能够使用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();
}

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

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

关于(略微修改的(代码:

//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永远不会执行,因为循环体不会运行始时为false,因为iwordVector.size()都为零。

如果你要修改循环,使主体运行,你会看到它也会在循环中失败

//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
}