使用 std::transform 在 2d C 阵列上转换为 1d C 数组

using std::transform on a 2d C array into a 1d C array

本文关键字:转换 1d 数组 阵列 transform 2d 使用 std      更新时间:2023-10-16

我正在尝试使用std::transform将一个简单的 2d 数组(Foo个结构(转换为 1d(转换(的Bar结构数组。

// convert 2d array of Foo structs to 1d array of Bar structs
// suitable for constructing a Baz struct.
Foo array2d[3][2] = 
{ 
{ 
{1,2}, {3,4} 
}, 
{ 
{5,6}, {7,8} 
}, 
{ 
{9,10}, {11,12} 
} 
};

这个简单示例中的转换只是颠倒了字段顺序,因为两个结构实际上是相同的类型。 在我的应用程序中,这些是完全不同的类型。

using Foo = struct {
uint32_t a;
uint32_t b;
};
using Bar = struct {
uint32_t c;
uint32_t d;
};

这个想法是这个 Bar 结构的 1d 数组可用于构造一个Baz结构。

我在使用λ转换器时遇到问题。 我相信外部的一次取一行,而内层在实际发生 Foo->Bar 转换的时间取一列。 在现场演示中,我不得不注释掉 std::transform 采用 2d 数组并将其替换为扁平化版本,其中我将 2d 数组转换为 1d 数组(大小为行乘以 col(。 这完美无缺 - 但我试图坚持使用参数类型,而不必求助于reinterpret_cast<>。

std::vector<Bar> array1d;
array1d.reserve(Baz::gArraySize);
#if 0
// I don't know how to use the transform on the 2d array
std::transform(std::cbegin(array2d), std::cend(array2d),
std::back_inserter(array1d),
[](const Foo(&rRow)[Baz::gNumCols]) {
std::transform(std::cbegin(rRow), std::cend(rRow),
[](const Foo& rNext) -> Bar {
// reverse the order of the fields
return Bar{ rNext.b, rNext.a };
});
});
#else
// Only workaround is to cast the 2d array to a 1d array using reinterpret cast<>
const auto& special = reinterpret_cast<const Foo(&)[Baz::gArraySize]>(array2d);
// I don't know how to use the transform on the 2d array
std::transform(std::cbegin(special), std::cend(special),
std::back_inserter(array1d),
[](const Foo& rNext) -> Bar {
// reverse the order of the fields
return Bar{ rNext.b, rNext.a };
});
#endif
// construct from transformed 2d array
Baz myBaz(reinterpret_cast<const Bar(&)[Baz::gArraySize]>(array1d[0]));
std::cout << myBaz;

生成预期输出,如下所示:

g++ -std=c++17 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
Bar{c=2, d=1},
Bar{c=4, d=3},
Bar{c=6, d=5},
Bar{c=8, d=7},
Bar{c=10, d=9},
Bar{c=12, d=11},

这些结构采用类似于 C 的数组形式,因为它们来自外部源。 我不确定我试图用 std::transform 做什么是否可行,但我想使用 STL 算法而不是手动解开循环。

我创建了以下实时 coliru 演示来展示我想要实现的目标 - 但它在转换时出现许多错误。 请注意,传递给 Baz 的数组取决于 std::vector 在内存中连续分配数据结构的事实(这是由 STL 保证的(。

struct Baz {
constexpr static int gNumRows = 3;
constexpr static int gNumCols = 2;
constexpr static int gArraySize = gNumRows * gNumCols;
Bar arrayField[gArraySize];
// explicit constructor from C style fixed size array.
explicit Baz(const Bar(&rParam)[gArraySize])
: arrayField{}
{
std::memcpy(arrayField, rParam, gArraySize * sizeof(Bar));
}
friend std::ostream& operator<<(
std::ostream& os, const Baz& rhs) {
for (auto next : rhs.arrayField) {
os << "Bar{c=" << next.c << ", d=" << next.d << "},n";
}
return os;
}
};

你传递给外部transform的lambda不返回任何内容,它真的不能,因为它应该为输入范围的每个元素(你的二维数组(返回一个值。但是该数组的每个元素都有两个值,因此transform的每次迭代都会产生两个值,而它应该产生一个值,这就是为什么你不能在这里使用transform

鉴于此,在这里使用简单的循环会容易得多,可读性也更强:

for (auto &&row : array2d)
for (auto &&foo : row)
oneDimArray.push_back(Bar{ foo.b, foo.a });

并将 STL 算法留给实际上使您的生活更轻松的情况:)。