我正在努力解决问题:使用MPI Scatter函数查找二维整数数组的所有唯一元素。如何修复?
Severity Code Description Project File Line Suppression State Detail Description
Warning C6001 Using uninitialized memory '*unique_counts'. ConsoleApplication15 C:\Users\netd3en\source\repos\ConsoleApplication15\ConsoleApplication15\ConsoleApplication15.cpp 29
#include <iostream>
#include <unordered_set>
#include <mpi.h>
int main(int argc, char* argv[]) {
int size, rank;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int arr[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
int* local_arr = new int[3];
MPI_Scatter(arr, 3, MPI_INT, local_arr, 3, MPI_INT, 0, MPI_COMM_WORLD);
std::unordered_set<int> unique_elements;
for (int i = 0; i < 3; i++) {
unique_elements.insert(local_arr[i]);
}
int* unique_counts = new int[size];
int local_unique_count = unique_elements.size();
MPI_Gather(&local_unique_count, 1, MPI_INT, unique_counts, 1, MPI_INT, 0, MPI_COMM_WORLD);
if (rank == 0) {
std::unordered_set<int> all_unique_elements;
int offset = 0;
for (int i = 0; i < size; i++) {
for (int j = 0; j < unique_counts[i]; j++) {
all_unique_elements.insert(local_arr[offset + j]);
}
offset += unique_counts[i];
}
std::cout << "Unique elements:";
for (auto it = all_unique_elements.begin(); it != all_unique_elements.end(); it++) {
std::cout << " " << *it;
}
std::cout << std::endl;
}
MPI_Finalize();
return 0;
}
1条答案
按热度按时间w1jd8yoj1#
你不初始化
unique_counts
指向的已分配int数组,MPI_Gather
可能会失败(你不检查返回值),并保持数组元素不变。不要忘记
delete[] unique_counts;