c++ - 如何使用 decltype 获取向量元素的类型作为模板参数
问题描述
这是我的代码的一部分:
int getLength(const vector<int> &arr) {
auto n=arr.size(),dis=n;
unordered_map<int,decltype(dis)> S;
//...
}
到目前为止,一切都很好。现在,我没有int
为 my 硬编码 "" std::unordered_map
,而是尝试将其更改为:
unordered_map<decltype(arr.front()),decltype(dis)> S;
or
unordered_map<decltype(arr)::value_type,decltype(dis)> S;
or
unordered_map<decltype(arr[0]),decltype(dis)> S;
似乎没有一个工作。在这里使用的正确语法是decltype()
什么?
解决方案
在这里使用 decltype 的正确语法是什么?
decltype(arr.front())
并且decltype(arr[0])
都可以,但不幸的是,它们都返回了对const的引用(考虑到这是一个常量向量) int
arr
您必须删除引用和常量,例如
std::unordered_map<
std::remove_const_t<std::remove_reference_t<decltype(arr.front())>>,
decltype(dis)> S;
使用::value_type
更好(恕我直言),因为你避免了常量,所以你必须只删除引用,所以你可以写
std::unordered_map<
std::remove_reference_t<decltype(arr)>::value_type,
decltype(dis)> S;
推荐阅读
- python - 在 Python Pandas 中将 1 分钟 OHLCV 数据重采样为 5 分钟数据
- reactjs - TypeError:无法读取未定义的属性“格式”
- ruby-on-rails - 将 Sinatra 语法转换为 Rails
- python - 特定窗口的键盘输入(python)
- javascript - CSS - 如何为文本设置永久位置,而不管上面出现的任何文本消息
- amazon-web-services - 获取 CWMetricData cmdlet 示例
- c - 将四个 16 位数字组合成一个 64 位数字
- sql - 查询 - 嵌套顶部 1 选择
- selenium - 在 Maven 项目中运行 Runner.java 时出错
- batch-file - RoboCopy 出现移动文件和目录的问题,但有例外