如何更改C++boost多数组中的元素类型
How to change type of elements in C++ boost multi array?
我从另一个函数收到一个包含unsigned char
类型元素的矩阵,我正在尝试找到它的最大值。
boost::multi_array<unsigned char, 2> matrix;
所有元素都是整数,所以我希望将矩阵重铸为类型<int, 2>
,然后执行std::max_element()
操作,但不确定如何重铸boost多数组的类型。
使用max_element
不需要这样。char
和int
:一样是积分型
实时编译器资源管理器
#include <boost/multi_array.hpp>
#include <fmt/ranges.h>
#include <algorithm>
int main() {
using boost::extents;
boost::multi_array<unsigned char, 2> matrix(extents[10][5]);
std::iota( //
matrix.data(), //
matrix.data() + matrix.num_elements(), 'x30');
fmt::print("matrix: {}n", matrix);
auto [a, b] = std::minmax_element(matrix.data(),
matrix.data() + matrix.num_elements());
// as integers
fmt::print("min: {}, max {}n", *a, *b);
// as characters
fmt::print("min: '{:c}', max '{:c}'n", *a, *b);
}
程序标准输出
matrix: {{48, 49, 50, 51, 52}, {53, 54, 55, 56, 57}, {58, 59, 60, 61, 62}, {63, 64, 65, 66, 67}, {68, 69, 70, 71, 72}, {73, 74, 75, 76, 77}, {78, 79, 80, 81, 82}, {83, 84, 85, 86, 87}, {88, 89, 90, 91, 92}, {93, 94, 95, 96, 97}}
min: 48, max 97
min: '0', max 'a'
重新解释视图
如果必须(由于使用max_element
的其他原因(,则可以使用multi_array_ref
:
// reinterpreting view:
boost::multi_array_ref<const char, 2> view(
reinterpret_cast<const char*>(matrix.data()),
std::vector(matrix.shape(), matrix.shape() + 2));
fmt::print("view: {}n", view);
它打印实时编译器资源管理器
view: {{'0', '1', '2', '3', '4'}, {'5', '6', '7', '8', '9'}, {':', ';', '<', '=', '>'}, {'?', '@', 'A', 'B', 'C'}, {'D', 'E', 'F', 'G', 'H'}, {'I', 'J', 'K', 'L', 'M'}, {'N', 'O', 'P', 'Q', 'R'}, {'S', 'T', 'U', 'V', 'W'}, {'X', 'Y', 'Z', '[', ''}, {']', '^', '_', '`', 'a'}}
你也可以重塑它:
view.reshape(std::vector{25, 2});
fmt::print("reshaped: {}n", view);
打印
reshaped: {{'0', '1'}, {'2', '3'}, {'4', '5'}, {'6', '7'}, {'8', '9'}, {':', ';'}, {'<', '='}, {'>', '?'}, {'@', 'A'}, {'B', 'C'}, {'D', 'E'}, {'F', 'G'}, {'H', 'I'}, {'J', 'K'}, {'L', 'M'}, {'N', 'O'}, {'P', 'Q'}, {'R', 'S'}, {'T', 'U'}, {'V', 'W'}, {'X', 'Y'}, {'Z', '['}, {'', ']'}, {'^', '_'}, {'`', 'a'}}
相关文章:
- C++ 未初始化的本地(非全局)int 数组中的元素类型到底是什么?
- 如何将 n 个连续元素插入到元素类型不可复制的 std::vector 中?
- 元函数使用 decltype 返回元素类型
- STDLIB中容器元素类型有什么要求?
- 使用 dectlype 推断模板元素类型中的数据类型是否正确?
- boost multi_index - 如果元素类型仅支持移动语义,如何遍历它?
- 打印/修改类对象的特定成员变量,其类定义列表 (STL) 包含的元素类型
- 使用声明中的元素类型隐式初始化 std::array
- 使用 SFINAE 和 void_t 来确定容器内的元素类型
- 键入 trait 以获取 std::array 或 C 样式数组的元素类型
- 如何在QTScript中将QLIST内部的QMAP注册为元素类型
- 关联容器,比较函数不是元素类型的一部分吗?
- 特征稀疏矩阵的 CoeffRef 中的错误,元素类型为向量
- 在编译时间检查模板参数类型是否设置或多键,并且容器的元素类型是算术的
- 从函数模板参数中自动推论对容器的元素类型
- 直接获取基于范围的循环中的元素类型 **例如"using"
- 定义指向 C++ 中相同元素类型的元素
- 如何在C++中一一阅读 CIN?元素类型不同
- 如何从STL容器实例中获取元素类型
- 容器的const_cast元素类型