2017-02-12 1 views
0

定数入力ストリームからのベクトルベクトルを設定します。 私はそれを行うことができますまた、以下のようにreadVector()メソッドを使用して構築されたベクトルを印刷することができます。C++:別の方法で返されたベクトルの定数ベクトルにアクセスする際のセグメンテーションエラー

しかし、私はそれが境界外のエラーを生成std::vectorat()ルーチンを使用して特定の値にアクセスしてみてください。私はベクトル全体を印刷することはできますが、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; 
} 

ラン:

入力(それぞれ2つの要素を持つ行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)の例と、デバッガで行った観察結果を表示します。 –

答えて

関連する問題