gpt4 book ai didi

c++ - 矩阵 vector 乘积函数的签名

转载 作者:搜寻专家 更新时间:2023-10-31 01:12:58 27 4
gpt4 key购买 nike

我是 C++ 的新手,仍然对如何将数组作为参数传递和返回感到困惑。我想写一个简单的 matrix-vector-product c = A * b 函数,签名如下

times(A, b, c, m, n)

其中A为二维数组,b为输入数组,c为结果数组,m nA 的维度。我想通过 mn 指定数组维度,而不是通过 A

(并行)函数的主体是

int i, j;
double sum;

#pragma omp parallel for default(none) private(i, j, sum) shared(m, n, A, b, c)
for (i = 0; i < m; ++i) {
sum = 0.0;
for (j = 0; j < n; j++) {
sum += A[i][j] * b[j];
}
c[i] = sum;
}
  1. 这样的函数的正确签名是什么?
  2. 现在假设我想在函数中创建结果数组 c 并返回它。我该怎么做?

最佳答案

因此,这里不是“你应该”的答案(我会放弃,因为你真的应该!),而是“你要求的”答案。

我会使用 std::vector保存数组数据(因为它们具有 O(1) 移动能力)而不是 std::array (这为您节省了间接费用,但移动成本更高)。 std::vectormalloc 的 C++“改进” 'd(和 realloc 'd)缓冲区,而 std::arraychar foo[27]; 的 C++“改进”样式缓冲区。

std::vector<double> times(std::vector<double> const& A, std::vector<double> const& b, size_t m, size_t n)
{
std::vector<double> c;
Assert(A.size() = m*n);
c.resize(n);

// .. your code goes in here.
// Instead of A[x][y], do A[x*n+y] or A[y*m+x] depending on if you want column or
// row-major order in memory.
return std::move(c); // O(1) copy of the std::vector out of this function
}

您会注意到我稍微更改了签名,以便它返回 std::vector 而不是将其作为参数。我这样做是因为我可以,而且它看起来更漂亮!

如果你真的必须通过 c在函数中,将其作为 std::vector<double>& 传递-- 对 std::vector 的引用.

关于c++ - 矩阵 vector 乘积函数的签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13198048/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com