在下面的(简化)代码中,我有一个类,其第一个成员是指向指针的指针(动态矩阵),我想知道如何使用scatterv和gatherv。我的目标是使用指向行的指针“水平”分割矩阵。
类:
#include <iostream>
using namespace std;
class Mat{
private:
int **m;
unsigned cols;
unsigned rows;
void allocate_mem(int ***ptr, unsigned r, unsigned c){
*ptr = new int *[r];
(*ptr)[0] = new int[r*c];
for(unsigned i = 1; i < r; i++)
(*ptr)[i] = (*ptr)[0] + i*c;
}
public:
Mat(){
rows = 1;
cols = 1;
allocate_mem(&m, 1, 1);
m[0][0] = 0;
}
Mat(unsigned n_rows, unsigned n_cols){
rows = n_rows;
cols = n_cols;
allocate_mem(&m, rows, cols);
for(unsigned i = 0; i < rows; i++)
for(unsigned j = 0; j < cols; j++)
m[i][j] = i+j;
}
Mat &operator=(const Mat &mrx){
int **new_ptr = NULL;
allocate_mem(&new_ptr, mrx.rows, mrx.cols);
for(unsigned i = 0; i < mrx.rows; i++)
for(unsigned j = 0; j < mrx.cols; j++)
new_ptr[i][j] = mrx[i][j];
delete[] m[0];
delete[] m;
m = new_ptr;
rows = mrx.rows;
cols = mrx.cols;
return *this;
}
const int *operator[](unsigned n) const{
return m[n];
}
void create_output(){
for(unsigned i = 0; i < cols; i++){
for(unsigned j = 0; j < rows; j++){
cout << m[i][j] << "\t";
}
cout << "\n";
}
}
~Mat(){
delete[] m[0];
delete[] m;
}
};
主:
#include "Mat.cpp"
#include <mpi.h>
#include <iostream>
using namespace std;
int main(int argc, char **argv){
MPI_Init(&argc, &argv);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int p;
MPI_Comm_size(MPI_COMM_WORLD, &p);
Mat m;
if(rank==0){
m = Mat(10,10);
cout << "First:" << endl;
m.create_output();
}
MPI_Barrier(MPI_COMM_WORLD);
//MPI_Scatterv();
//MPI_Gatherv();
if(rank==0){
cout << "Second:" << endl;
m.create_output();
}
MPI_Finalize();
return 0;
}