如何更改C++boost多数组中的元素类型

How to change type of elements in C++ boost multi array?

本文关键字:元素 类型 数组 何更改 C++boost      更新时间:2024-04-27

我从另一个函数收到一个包含unsigned char类型元素的矩阵,我正在尝试找到它的最大值。

boost::multi_array<unsigned char, 2> matrix;

所有元素都是整数,所以我希望将矩阵重铸为类型<int, 2>,然后执行std::max_element()操作,但不确定如何重铸boost多数组的类型。

使用max_element不需要这样。charint:一样是积分型

实时编译器资源管理器

#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'}}