2014-01-20 31 views
0

的矢量我有下面的代码,在那里我定义的结构如何填写结构

#include <vector> 
#include <iostream> 

using namespace std; 

struct node 
{ 
    int index; 
    double value; 
}; 

int main() 
{ 

    vector < vector <node> >vett1; 

    node p; 
    p.index=5; 
    p.value=2; 

    for (int i=0; i<10; i++) 
     vett1[i].push_back(p); 

    return 0; 
} 

的矢量的矢量我不知道正确的方式来填补它。通过这种方式,当我运行它,编译器给我分段错误的错误。

回答

0

当您访问vett1[i],但vett1尚未填充大小零。这就是分段错误发生的原因。

三种方式来解决这个问题:

  1. for循环之前添加

    vett1.resize(10); 
    

  2. 或定义vett1并设置其大小,如下所示:

    vector <vector <node>> vett1(10); 
    
  3. 或者你也可以做到这一点,如果你不知道确切的预定尺寸的手:

    for (int i=0; i<10; i++) 
    { 
        vector<node> temp; 
        temp.push_back(p); 
        vett1.push_back(temp); 
    } 
    
+0

如果我不知道矢量的确切大小怎么办?并且我想以与push_back方法相同的方式填充它? – zzari

+0

@ user2988113查看最新的答案。方法#3。 – herohuyongtao