我只能在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();
}
我只能在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,因为i
和wordVector.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
}
相关文章:
- 特征命名访问向量段
- 在无法访问向量的情况下查找迭代器的末尾
- 访问向量字段的键 - 枚举类还是命名空间中的枚举?
- 访问向量索引C++
- 如何通过迭代器访问向量中的嵌套对?
- 访问向量并将数据导出到文件
- 通用迭代器可以访问向量的元素,而无需使用模板C
- 如何使用指针访问向量元素的各个元素
- 使用 "find" 访问向量中的值
- 从触摸回调访问向量元素的方法时,不良访问错误
- 访问向量类中的成员变量
- 可以使用整数索引访问向量元素吗?
- 访问向量类成员时出现分段错误
- 从对象创建矢量包装器,该对象只允许使用索引访问向量
- C++ 访问向量动态数组中的违规读取位置0xFFFFFFFFFFFFFFFF
- 如何访问向量内的向量
- 访问向量C 中的分割故障
- 通过操作员[]和.at()访问向量的负索引
- 从DLL访问向量
- 用于访问向量的通用迭代器