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

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

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

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

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

您不需要它来使用 max_elementchar 是一个整数类型,就像 int:

Live On Compiler Explorer

#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);

打印 Live On Compiler Explorer

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