2013-05-22 33 views
-1

我在一段时间内还没有完成C++。在一个向量中打印数据

我试图得到一个矢量矢量打印数据。我得到以下错误:

Segmentation fault (core dumped)

我使用的是网上编译运行的代码。

#include <iostream>  // std::cout 
#include <algorithm> // std::for_each 
#include <vector>  // std::vector 

void myfunctiontwo (int i) { // function: 
    std::cout << ' ' << i; 
} 

void myfunction (std::vector<int> myvector) { // function: 
    for_each (myvector.begin(), myvector.end(), myfunctiontwo); 
} 

int main() { 
    // create a vector of vectors. 
    std::vector< std::vector<int> > myvector; 

    // add some data 
    myvector[0].push_back(10); 
    myvector[1].push_back(20); 
    myvector[2].push_back(30); 

    std::cout << "myvector contains:"; 
    for_each (myvector.begin(), myvector.end(), myfunction); 
    std::cout << '\n'; 

    return 0; 
} 
+1

它应该是std :: vector > myvector(3)? –

+1

@PoiXen:对,对不起,我是盲人。但是看看[漂亮打印机](http://stackoverflow.com/q/4850473/596781):-) –

回答

3

你的问题是推背:

myvector[0].push_back(10); 
myvector[1].push_back(20); 
myvector[2].push_back(30); 

myvector[0]myvector[1]myvector[2]还不存在的载体。如果你想myvector开始用3个向量,就可以像这样创建:

std::vector< std::vector<int> > myvector(3); 
+1

更好的是,'myvector = {{10},{20},{30}}': - ) –

+0

@KerrekSB是的。不过,我怀疑他们从他们使用C++ 03格式化模板参数的方式。 –

0

,你可以从以下链接http://www.cplusplus.com/reference/vector/vector/operator [见] /,运算符[]是访问元素 这是你不能用它插入元素的方式。插入对象使用分配,push_back和插入