(I didn't write this code. This is an existing piece of code from UC Berkeley's parallel algorithms homework which I should parallelize using Pthreads)
There is this piece of code in my Parallel Algorithms homework's `int main()` function:
particle_t *particles = (particle_t*) malloc( n * sizeof(particle_t) );
init_particles( n, particles );
vector<particle_t*> *bins = new vector<particle_t*>[numbins];
with `particle_t` being defined outside of the `int main()` as:
void init_particles( int n, particle_t *p )
{
srand48( time( NULL ) );
int sx = (int)ceil(sqrt((double)n));
int sy = (n+sx-1)/sx;
int *shuffle = (int*)malloc( n * sizeof(int) );
for( int i = 0; i < n; i++ )
shuffle[i] = i;
for( int i = 0; i < n; i++ )
{
//
// make sure particles are not spatially sorted
//
int j = lrand48()%(n-i);
int k = shuffle[j];
shuffle[j] = shuffle[n-i-1];
//
// assign random velocities within a bound
//
p[i].vx = drand48()*2-1;
p[i].vy = drand48()*2-1;
}
free( shuffle );
}
The piece of code I can't understand is here
// clear bins at each time step
for (int m = 0; m < numbins; m++)
bins[m].clear();
// place particles in bins
for (int i = 0; i < n; i++)
bins[binNum(particles[i],bpr)].push_back(particles + i);
As I understand, the cells of `bins`, are pointers to `particle_t` objects, and not vectors themselves. Unfortunately in the first loop, `bins`'s cells have been treated as vectors themselves, because `.clear()` function has been used on them. In the second loop as well, `bins`'s cells have been treated as vectors themselves by using `.push_back()` on them. Where is the misunderstanding? The code compiles successfully.
Unfortunately in the first loop, `bins`'s cells have been treated as vectors themselves, because `.clear()` function has been used on them.
No, what you have is an array of vectors which means basically 2D. So in the first loop bins[m] addresses the vector itself not the element of the vector.
So you miss one dimension that's the problem.
vector<particle_t*> *bins = new vector<particle_t*>[numbins]; // creates an array of vectors
or, you misread it.
new works like this:
pointer = new type; //one item
or this:
pointer = new type[count]; //'array' of 'type' with 'count' number of items
all the template stuff in your example may be making it hard to read if you are shaky on pointer syntax or template syntax.
breaking it down a little more, then, carefully.
bins is a pointer. it points to a block of memory that represent an array.
each location of the array, eg bins[42], is a vector.
each vector location, eg bins[42][13] is a particle_t pointer. If those are allocated as arrays as well, then
bins[42][13][5] is a 3d hop to a particle_t