简体   繁体   中英

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. 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.


#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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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