python - 如何在 C++ 中创建类似于 Python 的 numpy 数组的数组?

标签 python c++ c++11 numpy

我正在将 Python 程序转换为 C++ 格式。

Python 具有以下格式的数组。

boxes = np.zeros((1, 300, 4, 5, 1), dtype = np.float)

创建功能类似于 boxes 数组的 C++ 数组的最佳方法是什么?

最佳答案

事实上,numpy 分配了一个连续的数组存储和 strides用于基于多维索引计算内存偏移量。要在 C++ 中获得类似的结果,您可以编写如下代码:

#include <vector>
#include <memory>
#include <cstddef>
#include <cstdio>

class NDArray {
    std::vector<size_t> m_dims, m_strides;
    std::unique_ptr<float[]> m_buf;

    public:
        NDArray(std::vector<size_t> dims):
            m_dims{std::move(dims)}
        {
            m_strides.resize(m_dims.size());
            size_t stride = 1;
            for (int i = m_dims.size() - 1; i >= 0; -- i) {
                m_strides[i] = stride;
                stride *= m_dims[i];
            }
            m_buf.reset(new float[stride]);
        }

        float& operator[] (std::initializer_list<size_t> idx) {
            size_t offset = 0;
            auto stride = m_strides.begin();
            for (auto i: idx) {
                offset += i * *stride;
                ++ stride;
            }
            return m_buf[offset];
        }
};

int main() {
    NDArray arr({2, 3});
    arr[{1, 2}] = 3;
    arr[{1, 1}] = 2;
    printf("%g\n", arr[{1, 2}]);
}

关于python - 如何在 C++ 中创建类似于 Python 的 numpy 数组的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43756234/

相关文章:

c++ - ASIO signal_set对多个IO线程不可靠,取决于代码顺序?

c++ - C++ 迭代器的生命周期和有效性是多少?

c++ - 错误实现的强类型枚举的语法?

python - 定时器可重新启动

python - Web 应用程序可在本地计算机上运行,​​但不能在 Heroku 上运行

c++ - Qt Sqlite 更新返回 false

c++11 - 迭代时添加到集合 (C++)

c++ - 自动生成成员函数的 const 重载

python - 使用现有实例初始化 super?

python - 如何有条件地更改数组值