如何确定数组元素的类型?

NuP*_*adi 5 c++ arrays vector c++11

我无法获得元素的类型.此解决方案返回对元素类型的引用.

int arr[] = { 0, 1, 2, 3, 4, 5 };
using arrElemType = decltype(*arr);
vector<arrElemType> vec(std::cbegin(arr), std::cend(arr));
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 10

请尝试以下方法

using arrElemType = std::remove_reference<decltype( *arr )>::type;
Run Code Online (Sandbox Code Playgroud)

要么

typedef std::remove_reference<decltype( *arr )>::type arrElemType;
Run Code Online (Sandbox Code Playgroud)

你需要包含标题 <type_traits>

  • @ user2198121:只是因为碰巧是通过其他标题间接包含的.你不应该依赖它. (9认同)

Ben*_*n T 7

C++11 及更高版本中的标准方法是使用std::remove_all_extents.

#include <type_traits>

int arr[] = { 0, 1, 2, 3, 4, 5 };
using arrElemType = std::remove_all_extents<decltype(arr)>::type;
vector<arrElemType> vec(std::cbegin(arr), std::cend(arr));
Run Code Online (Sandbox Code Playgroud)