xtensor 简介
xtensor 是一个用于数值分析的 C++ 库,它提供了多维数组表达式的功能。这个库的主要特点包括:
- 延迟广播(Lazy Broadcasting):提供了一个可扩展的表达式系统,允许延迟计算。
- 符合 C++ 标准库的 API:其 API 设计遵循 C++ 标准库的惯例。
- 数组表达式操作工具:提供了工具来操作数组表达式,并在 xtensor 基础上进行构建。
xtensor 的容器设计灵感来自于 Python 的 NumPy 库。它还支持通过 Python 的缓冲协议直接处理 NumPy 数据结构。此外,xtensor 还提供了对 R 和 Julia 的语言绑定。
系统要求
xtensor 需要一个支持 C++14 的现代 C++ 编译器。支持的编译器包括:
- Windows 平台:Visual C++ 2015 Update 2 或更新版本
- Unix 平台:gcc 4.9 或 Clang 的最新版本
主要函数和类
xtensor_container
xtensor_container
是一个密集的多维容器,具有张量语义和固定维度。以下是一些构造函数和方法:
xtensor_container()
:构造一个未初始化的xtensor_container
,包含 0 个元素。xtensor_container(nested_initializer_list_t<value_type, N> t)
:使用嵌套初始化列表构造xtensor_container
。xtensor_container(const shape_type& shape, layout_type l = L)
:根据指定的形状和布局类型构造xtensor_container
。xtensor_container(const shape_type& shape, const_reference value, layout_type l = L)
:构造一个初始化为指定值的xtensor_container
。xtensor_container(const shape_type& shape, const strides_type& strides)
:根据指定的形状和步长构造xtensor_container
。xtensor_container(storage_type&& storage, inner_shape_type&& shape, inner_strides_type&& strides)
:通过移动指定的数据、形状和步长构造xtensor_container
。
xtensor_adaptor
xtensor_adaptor
是一个密集的多维容器适配器,具有张量语义和固定维度。它用于为类似 STL 的容器提供多维容器语义和张量语义。以下是一些构造函数和方法:
xtensor_adaptor(storage_type&& storage)
:构造一个适配给定 STL 容器的xtensor_adaptor
。xtensor_adaptor(const storage_type& storage)
:构造一个适配给定 STL 容器的xtensor_adaptor
。xtensor_adaptor(D&& storage, const shape_type& shape, layout_type l = L)
:构造一个适配给定 STL 容器的xtensor_adaptor
,并指定形状和布局类型。xtensor_adaptor(D&& storage, const shape_type& shape, const strides_type& strides)
:构造一个适配给定 STL 容器的xtensor_adaptor
,并指定形状和步长。
xtensor_view
xtensor_view
是一个密集的多维容器适配器,具有视图语义和固定维度。它用于为类似 STL 的容器提供多维容器语义和视图语义。以下是一些构造函数和方法:
xtensor_view(storage_type&& storage)
:构造一个适配给定 STL 容器的xtensor_view
。xtensor_view(const storage_type& storage)
:构造一个适配给定 STL 容器的xtensor_view
。xtensor_view(D&& storage, const shape_type& shape, layout_type l = L)
:构造一个适配给定 STL 容器的xtensor_view
,并指定形状和布局类型。xtensor_view(D&& storage, const shape_type& shape, const strides_type& strides)
:构造一个适配给定 STL 容器的xtensor_view
,并指定形状和步长。
示例
以下是一个简单的示例,展示如何使用 xtensor_container
:
#include <iostream>
#include <vector>
#include "xtensor/xtensor.hpp"
int main()
{
// 创建一个 3x3 的 xtensor_container,并初始化为 1
xt::xtensor<int, 2> a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// 打印 xtensor_container
for (auto& row : a)
{
for (auto& elem : row)
{
std::cout << elem << " ";
}
std::cout << std::endl;
}
// 创建一个 xtensor_adaptor
std::vector<int> data = {1, 2, 3, 4, 5, 6, 7, 8, 9};
xt::xtensor<int, 2> b(data, {3, 3});
// 打印 xtensor_adaptor
for (auto& row : b)
{
for (auto& elem : row)
{
std::cout << elem << " ";
}
std::cout << std::endl;
}
return 0;
}
这个示例首先创建了一个 3x3 的 xtensor_container
并初始化为 1,然后创建了一个 xtensor_adaptor
并使用一个 std::vector
作为其存储容器。最后,示例打印了这两个容器的内容。