#include <mpi.h>
#include<vector>
void t12(int argumentcount, char* argumentvector[]) {
int myid, numprocs;
int namelen;
char processor_name[MPI_MAX_PROCESSOR_NAME];
MPI_Init(&argumentcount, &argumentvector);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
MPI_Get_processor_name(processor_name, &namelen);
MPI_Status status;
std::vector<int> vec;
int vec_size;
if (myid == 0) {
vec = { 1, 2 }; //进程0赋值
vec_size = vec.size();
}
MPI_Bcast(&vec_size, 1 * sizeof(int), MPI_BYTE, 0, MPI_COMM_WORLD);
if (myid > 0)
vec.resize(vec_size);
MPI_Bcast(vec.data(),
vec.size() * sizeof(int),
MPI_BYTE,
0,
MPI_COMM_WORLD);
}
这是一重向量
下面是2重向量
#include <mpi.h>
#include<vector>
#include<iostream>
void t2(int argumentcount, char* argumentvector[]) {
int myid, numprocs;
int namelen;
char processor_name[MPI_MAX_PROCESSOR_NAME];
MPI_Init(&argumentcount, &argumentvector);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
MPI_Get_processor_name(processor_name, &namelen);
MPI_Status status;
std::vector<std::vector<int>> inds;
int inds_size;
std::vector<int> inds_i_size;
if (myid == 0) {
//在进程0里获取inds
for (int i1 = 0; i1 < 2; ++i1) {
for (int i3 = 0; i3 < 4; ++i3) {
std::vector<int> ind{ i1, i3 };
inds.emplace_back(ind);
}
}
inds_size = inds.size();
inds_i_size.resize(inds.size());
for (int i = 0; i < inds.size(); ++i) {
inds_i_size[i] = inds[i].size();
for (int j = 0; j < inds[i].size(); ++j) {
std::cout << "inds[" << i << "][" << j << "]=" << inds[i][j] << ", ";
}
std::cout << std::endl;
}
}
MPI_Bcast(&inds_size, 1 * sizeof(int), MPI_BYTE, 0, MPI_COMM_WORLD);
//先广播inds的外层的大小
if (myid > 0)
inds_i_size.resize(inds_size);
//再广播inds的内层的向量的大小
MPI_Bcast(inds_i_size.data(), inds_i_size.size() * sizeof(int), MPI_BYTE, 0,
MPI_COMM_WORLD);
//然后在其他进程里开辟外层向量的空间大小,然后再开辟内层的向量的空间
if (myid > 0) {
inds.resize(inds_size);
for (int i = 0; i < inds.size(); ++i)
inds[i].resize(inds_i_size[i]);
}
//然后在其他进程里广播内层向量
for (int i = 0; i < inds.size(); ++i) {
MPI_Bcast(inds[i].data(), inds[i].size() * sizeof(int), MPI_BYTE, 0,
MPI_COMM_WORLD);
}