使用带有 MPI_Gather 的 std::vector 崩溃,而 c 样式数组工作正常

Using std:: vector with MPI_Gather crashes while c-style array works fine

我正在练习这段代码,它适用于 C 风格的数组,但不适用于 std::vector。我不知道问题所在,但似乎无法终止该过程。有谁知道这个实现有什么问题吗?

#include <fstream>
#include <iostream>
#include <vector>
#include "mpi.h"
using namespace std;
const int N = 3;
    
int main()
{
    MPI_Init(NULL, NULL);
    int rank;
    int size;
    int root = 0; 
    vector<int> x(N);
    //int x[N]; 
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);
        
    //int leng = size * N; 
    const int leng = 4 * N; 
    vector<int> single_arr(leng);
    //int single_arr[leng];
    
    for (int i = 0; i < N;i++) {
        x[i] = rank + i; 
        cout << x[i] << endl; 
    }
    
    MPI_Gather(&x, N, MPI_INT, &single_arr, N, MPI_INT, root, MPI_COMM_WORLD);
    MPI_Finalize();
}

您不能只使用 std::vector 的地址,因为 C 样式数组需要作为参数。相反,使用 data() member function:

    MPI_Gather(x.data(), N, MPI_INT, &single_arr, N, MPI_INT, root, MPI_COMM_WORLD);

或者(特别是如果您使用的是 C++11 之前的编译器),您可以传递向量的第一个元素的地址:

    MPI_Gather(&x[0], N, MPI_INT, &single_arr, N, MPI_INT, root, MPI_COMM_WORLD);

由于组成任何 std::vector 的元素 保证 是连续的,因此其第一个元素的地址对于期望(类似连续) 'old-style'数组。但是请注意,如果向量为空,以上两种方法都不起作用。