简体   繁体   English

打印向量数组 C++

[英]Printing an array of vectors c++

for a simple 1D vector I can print out the elements of the vector easily like this.对于一个简单的一维向量,我可以像这样轻松打印出向量的元素。

#include <iostream> 
#include <vector> 
using namespace std; 
  
int main() 
{ 
    vector<double> myvector; 
    for(int i=0; i<10; i++){
      myvector.push_back(i*2.0); 
    }
   
    for (auto it = myvector.begin(); it != myvector.end(); ++it) 
        cout << ' ' << *it; 
} 

In the same way, now I want to create some arrays of vectors and then wanna push-back the elements of the vector arrays, and then I want to print them.以同样的方式,现在我想创建一些向量数组,然后想要推回向量数组的元素,然后我想打印它们。 The way have done is:已经完成的方法是:

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

int main()
{


vector<double> array[10];

for(int j=1; j<=10; j++){

    for(int i =0; i<=5; i++){
        array[j].push_back(i*j*2);
    }
}

for (int j=1; j<10;j++){
 for (auto it = array[j].begin(); it != array[j].end(); ++it) 
    cout << ' ' << *it; 
 }
}

The later one is showing some segmentation errors.后一个显示一些分段错误。 Can you suggest how to do the second one (array of vectors) correctly?你能建议如何正确地做第二个(向量数组)吗?

You will have to use 2D array instead of 1D array.您将不得不使用二维数组而不是一维数组。 array[j].push_back(i*j*2) is completely wrong. array[j].push_back(i*j*2)是完全错误的。 You can either do arr[j]=i*j*2 if you want to use 1D vector but since you want to push multiple elements at one position you have got to use 2D vector then you can push multiple elements at a particular position which is your final objective I guess.如果您想使用一维向量,您可以执行arr[j]=i*j*2但由于您想在一个位置推送多个元素,您必须使用二维向量,那么您可以在特定位置推送多个元素我猜是你的最终目标。


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

int main()
{


vector<vector<double>> array(10);

for(int j=0; j<10; j++){

    for(int i=0; i<=5; i++){
        array[j].push_back(i*j*2);
    }
}

for (int j=0; j<10;j++){
 for (auto it = array[j].begin(); it != array[j].end(); ++it) 
    cout << ' ' << *it; 
 }
}

Also, check the way the size of the vector should be pre-defined and how to use a 2D vector.此外,请检查应预定义矢量大小的方式以及如何使用 2D 矢量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM