gpt4 book ai didi

c++ - 如何从 vector 初始化数组? (如何将指针转换为数组?)

转载 作者:行者123 更新时间:2023-11-27 22:51:23 26 4
gpt4 key购买 nike

我正在尝试从 std::vector 的数据构建一个 std::array。我目前已经这样做了:

#include <vector>
#include <array>

int main(void)
{
std::vector<int> vec{{1, 2, 3, 4, 5}};
std::array<int, 5> arr{static_cast<int [5]>(vec.data())};

(void)arr;
return 0;
}

但是 gcc 不接受这个转换:

error: invalid static_cast from type ‘int*’ to type ‘int [5]’

我认为数组可以用作指针,但为什么我们不能进行这种转换?

编辑:这不是 Copy std::vector into std::array 的拷贝因为我的问题是关于 std::array初始化(构造);不要复制进去。

编辑:我已经这样做了:

#include <vector>
#include <array>

int main(void)
{
std::vector<int> vec{{1, 2, 3, 4, 5}};
int *a(vec.data());
std::array<int, 5> arr{*reinterpret_cast<int (*)[5]>(&a)};

(void)arr;
return 0;
}

但是数组没有初始化... gcc 说:

error: array must be initialized with a brace-enclosed initializer

最佳答案

“我认为数组可以用作指针,但为什么我们不能进行这种转换?”

您可以将数组用作指针,因为它们会“衰减”到它们。参见 "What is array decaying?"

但反之则不然。 (对不同大小的数组也有类型检查。)

虽然 static_cast 可用于反转一些 隐式转换,但这不是其中之一。明确是 excluded from the list :

5) If a standard conversion sequence from new_type to the type of expression exists, that does not include lvalue-to-rvalue, array-to-pointer, function-to-pointer, null pointer, null member pointer, function pointer, (since C++17) or boolean conversion, then static_cast can perform the inverse of that implicit conversion.

所以这可能会让您想知道如何将指针转换为数组类型。你不能,因为 "Arrays are second-class citizens in C (and thus in C++)." reinterpret_cast 也不起作用。

(如果您尝试使用像 (int [5])(vec.data()) 这样的 C 风格转换,您可能会得到更明确的消息 ISO C++ 禁止转换到数组类型“int [5]”。)

这就是语言实现失败的原因。在这里,您正在做的是尝试初始化一个 std::array,其存在的理由实际上只是 wrap a C array。 :

This container is an aggregate type with the same semantics as a struct holding a C-style array T[N] as its only non-static data member.

因此,当涉及到初始化形式时,它无法完成您对 C 数组无法完成的任何事情。如果您手中有一个整数指针并想从该指针初始化一个 int arr[5] = ...,您同样会倒霉。你必须复制它。

在这种情况下,可以用...来完成

Copy std::vector into std::array

关于c++ - 如何从 vector 初始化数组? (如何将指针转换为数组?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36934459/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com