I have a function with a vector that is passed in by reference. I am able to use the vector inside a for loop to write its contents to a file. However, if I try to access any index of the vector outside of the loop, is gives me this error:
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)
Here is my code:
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
No, you can access elements of a vector anywhere where the vector is is scope. But you need to ensure you're accessing actual elements, not made-up ones :-)
With regard to the (slightly modified) code:
//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
}
When the vector is empty, the cout
inside the loop is never executed, because the loop body doesn't run. That's because i < wordVector.size()
starts out as false because both i
and wordVector.size()
are zero.
If you were to modify the loop so that the body did run, you would see it also fails within the loop:
//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
}