我的目标是从输入流中填充向量向量常量。 我可以这样做,并使用readVector()
方法打印构建的矢量,如下所示。C++:在访问由另一种方法返回的向量的常量向量时出现分段错误
但是当我尝试使用at()
常规它所产生的误差出界的std::vector
的访问特定的值。尽管我可以打印整个矢量,但我甚至无法访问2d矢量的[0,0]元素。
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
inline const int myread() {
int n;
cin >> n;
return n;
}
const vector< vector <int> > readVector (const int &n) {
int i, j;
vector< vector <int> > v (n);
// Populate the vector v.
for (i = 0; i < n; i++) {
const int rs = myread(); // row size
// construct an internal vector (iv) for a row.
vector <int> iv(rs);
for (j = 0; j < rs; j++) {
cin >> iv[j];
}
// Append one row into the vector v.
v.push_back (iv);
}
return v;
}
int main() {
const int n = myread();
// Construct a 2d vector.
const vector< vector <int> > v (readVector (n));
// Prints the vector v correctly.
for (vector <int> k : v) {
for (int l : k) {
cout << l << " ";
}
cout << endl;
}
// Produces the out of bounds error shown below
cout << v.at(0).at(0);
return 0;
}
一个运行:
输入:(分别两排,元件
1, 5, 4
和1, 2, 8, 9, 3
,)
2 3 1 5 4 5 1 2 8 9 3
输出:
1 5 4 1 2 8 9 3
terminate called after throwing an instance of 'std::out_of_range' what(): vector::_M_range_check: __n (which is 0) >= this->size() (which is 0)
我是新来C++
。请帮帮我。
解决此类问题的正确工具是您的调试器。在*堆栈溢出问题之前,您应该逐行执行您的代码。如需更多帮助,请阅读[如何调试小程序(由Eric Lippert撰写)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,你应该[编辑]你的问题,包括[最小,完整和可验证](http:// stackoverflow。com/help/mcve)示例,它再现了您的问题以及您在调试器中的观察结果。 –