C++ C++;:访问另一种方法返回的向量的常量向量时出现分段错误
我的目标是从输入流中填充一个恒定的向量。 我可以这样做,还可以使用C++ C++;:访问另一种方法返回的向量的常量向量时出现分段错误,c++,vector,C++,Vector,我的目标是从输入流中填充一个恒定的向量。 我可以这样做,还可以使用readVector()方法打印构造的向量,如下所示 但是,当我尝试使用std::vector的at()例程访问特定值时,它会产生超出范围的错误。我甚至无法访问2d向量的[0,0]元素,尽管我可以打印整个向量 #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <al
readVector()
方法打印构造的向量,如下所示
但是,当我尝试使用std::vector
的at()
例程访问特定值时,它会产生超出范围的错误。我甚至无法访问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;
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
内联常量int myread(){
int n;
cin>>n;
返回n;
}
常量向量readVector(常量int&n){
int i,j;
向量v(n);
//填充向量v。
对于(i=0;i>iv[j];
}
//在向量v中追加一行。
v、 推回(iv);
}
返回v;
}
int main(){
常量int n=myread();
//构造一个二维向量。
常数向量v(readVector(n));
//正确打印向量v。
对于(向量k:v){
for(int l:k){
问题是这条线
vector< vector <int> > v (n);
将新向量推到空向量之后。您应该使用赋值或使用
vector< vector <int> > v;
vectorv;
只需打印矢量大小
std::cout << v.size() << std::endl;
std::cout问题是线路
vector< vector <int> > v (n);
将新向量推到空向量之后。您应该使用赋值或使用
vector< vector <int> > v;
vectorv;
只需打印矢量大小
std::cout << v.size() << std::endl;
另一种解决方法是声明如下向量数组:
vector< int > v (n);
这在以后需要通过索引访问向量时很有用。另一种解决方法是声明如下向量数组:
vector< int > v (n);
当您以后需要通过索引访问vector时,这将非常有用。解决此类问题的正确工具是调试器。在询问堆栈溢出问题之前,您应该逐行检查代码。有关更多帮助,请阅读。至少,您应该[编辑]您的问题包括一个重现您的问题的示例,以及您在调试器中所做的观察。解决此类问题的正确工具是调试器。在询问堆栈溢出问题之前,您应该逐行检查代码。有关更多帮助,请阅读。至少,您应该[编辑]您的问题包括一个重现您的问题的示例,以及您在调试器中所做的观察。