简体   繁体   中英

Create a 2D array using vector (C++) from a set of available points

I have a set of points generated using the function linspace (similar to the one in MATLAB):

vector<double> x_coord = linspace(-5,5,11); // Output = -5 -4 -3 -2 -1 0 1 2 3 4 5 
vector<double> y_coord = linspace(-5,5,11); // Output = -5 -4 -3 -2 -1 0 1 2 3 4 5 

vector<vector<double>> coord( x_coord.size() , vector<double> (3));

 for(int i=0; i<x_coord.size();i++){
    for(int j=0; j<x_coord.size();j++){
        coord[i] = {x_coord[i],y_coord[j],0};
  }
 }

I want to create a 2D array "coord" using this set of points such that i have a square shaped grid. I tried doing it using the nested for loops as above but didn't get the result i wanted. Essentially coord array should be like:

-5,-5,0
-5,-4,0
-5,-3,0
-5,-2,0
-5,-1,0
-5,0,0
-5,1,0
-5,2,0
-5,3,0
-5,4,0
-5,5,0
-4,-5,0
-4,-4,0
.
.
-4,4,0
-3,-5,0
-3,-5,0
.
.
-3,5,0
.
.
.
.
5,5,0

How do i construct the array coord?

Just keep it simple, use push_back and a range-for loop:

vector<vector<double>> coord;
coord.reserve(x_coord.size() * y_coord.size());
for(auto x : x_coord){
  for(auto y : y_coord){
    coord.push_back({x,y,0});
  }
}

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