2017-02-12 77 views
0

我的目标是从输入流中填充向量向量常量。 我可以这样做,并使用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, 41, 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++。请帮帮我。

+1

解决此类问题的正确工具是您的调试器。在*堆栈溢出问题之前,您应该逐行执行您的代码。如需更多帮助,请阅读[如何调试小程序(由Eric Lippert撰写)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,你应该[编辑]你的问题,包括[最小,完整和可验证](http:// stackoverflow。com/help/mcve)示例,它再现了您的问题以及您在调试器中的观察结果。 –

回答

2

的问题是,该线

vector< vector <int> > v (n); 

已经创建包含的intn矢量各自具有大小为0的线

v.push_back (iv); 

后推新的矢量一个矢量空载体。您应该使用赋值或

vector< vector <int> > v; 

创建一个空的载体,只输出矢量大小

std::cout << v.size() << std::endl; 

在每个迭代中,看看会发生什么。

1

另一种方式来解决这个问题的声明向量数组是这样的:

vector<int> v (n); 

,然后存储载体:

v[i].push_back (iv); 

这是很有帮助的,当你需要通过指数稍后访问矢量。