2014-09-19 47 views
6

我想通過使用兩個索引將值添加到2D矢量。當我運行我的程序時,我收到窗口消息說程序已停止工作。使用Dev-C++進行調試表明存在分段錯誤(我不確定這意味着什麼)。請不要使用數組,我必須使用矢量來完成這個任務。通過使用索引爲2D矢量分配值

#include <iostream> 
#include <vector> 
using namespace std; 

int main(int argc, char** argv) { 

vector< vector<int> > matrix; 
cout << "Filling matrix with test numbers."; 
for (int i = 0; i < 4; i++) { 
    for (int j = 0; j < 4; j++) { 

     matrix[i][j] = 5; // causes program to stop working 

    } 
} 
} 

我創造,我想填補一個3X3矩陣值5的測試情況下,我懷疑它是與沒有被明確定義的二維矢量的大小。如何使用索引來填充具有值的2D矢量?

回答

9

正如所寫,這是有問題的,你正試圖寫入一個你尚未分配內存的向量。

選項1 - 調整您的載體提前

vector< vector<int> > matrix; 
cout << "Filling matrix with test numbers."; 
matrix.resize(4); // resize top level vector 
for (int i = 0; i < 4; i++) 
{ 
    matrix[i].resize(4); // resize each of the contained vectors 
    for (int j = 0; j < 4; j++) 
    { 
     matrix[i][j] = 5; 
    } 
} 

選項2 - 大小的矢量,當你把它聲明

vector<vector<int>> matrix(4, vector<int>(4)); 

選項3 - 使用push_back根據需要調整向量。

vector< vector<int> > matrix; 
cout << "Filling matrix with test numbers."; 
for (int i = 0; i < 4; i++) 
{ 
    vector<int> temp; 
    for (int j = 0; j < 4; j++) 
    { 
     temp.push_back(5); 
    } 
    matrix.push_back(temp); 
} 
+0

爲什麼必須有矩陣[I] .resize( 4)在for循環內? – AvP 2014-09-19 15:33:26

+0

因爲你有一個向量向量。所以每個內部向量需要大小爲4,那麼外部向量包含4個內部向量。 – CoryKramer 2014-09-19 15:34:12

+0

對於我的情況,我希望這個2D矢量代表一個3x3矩陣。所以不應該是矩陣[我] .resize(3),外部向量將包含3這些? – AvP 2014-09-19 15:39:54

3

你還沒有爲你的2D矢量分配任何空間。因此,在你當前的代碼中,你試圖訪問一些不屬於你的程序內存空間的內存。這將導致分段錯誤。

嘗試:

vector<vector<int> > matrix(4, vector<int>(4)); 

如果你想給所有的元素相同的值,你可以嘗試:

vector<vector<int> > matrix(4, vector<int>(4,5)); // all values are now 5 
0
vector<int> v2d1(3, 7); 
    vector<vector<int> > v2d2(4, v2d1); 
    for (int i = 0; i < v2d2.size(); i++) { 
     for(int j=0; j <v2d2[i].size(); j++) { 
        cout<<v2d2[i][j]<<" "; 
       } 
       cout << endl; 
      } 
+0

Hello Mohammad,歡迎來到stackoverflow。請添加您的答案的主要想法和變化,而不僅僅是代碼。 – 2015-07-02 21:22:13