gpt4 book ai didi

c++ - 将 numpy 数组公开为 C++ vector

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:44:01 25 4
gpt4 key购买 nike

使用 PyArray_SimpleNewFromData,很容易将 std::vector 公开为 numpy 数组。我现在正试图做相反的事情:将 numpy 数组公开为 C++ vector 。

暴露为 C 数组是可能的:

// get the size
npy_intp s = PyArray_SIZE(numpy_array);
// get the pointer to the array
bool* c_array = (bool*) PyArray_GETPTR1( numpy_array, 0 );
// Do something
for(unsigned int i=0; i<s; i++)
c_array[i] = ... ;

现在用 c++ vector 代替 c 数组怎么样?

编辑:我不想复制数据,否则答案是微不足道的。

最佳答案

假设您不想只将数据复制到 std::vector 中,你可能会发现 std::reference_wrapper 有用。

int main()
{
std::vector<int> numpy_array_{ 1, 2, 3, 4 };
const auto s = numpy_array_.size();
auto arr = numpy_array_.data();

// ...

for (size_t i = 0; i < s; i++)
arr[i] += 10;

const std::vector<std::reference_wrapper<int>> v(arr, arr + s);
void f(const std::vector<std::reference_wrapper<int>>&);
f(v);

return 0;
}

void f(const std::vector<std::reference_wrapper<int>>& v)
{
for (size_t i = 0; i < v.size(); i++)
v[i] += 100;
}

请注意 std::vectorconst这样大小就不能改变;这使 C 样式数组保持为“主”。

当然,您可以轻松地将数据复制到std::vector<> 中也是:

std::vector<int> v(arr, arr + s);

...甚至在必要时再次复制它(假设大小相同或更小)

std::copy(v.begin(), v.begin()+s, arr);

最后,请注意 std::vector<bool> 是特殊的,不会像普通的 C 风格数组那样工作。

关于c++ - 将 numpy 数组公开为 C++ vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42931932/

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