C++ 通过decltype声明一个向量

C++ 通过decltype声明一个向量,c++,c++11,c++14,type-inference,decltype,C++,C++11,C++14,Type Inference,Decltype,问题是decltype(c.begin()->first)返回一个const int(当使用libstdc++时-您的示例使用libc++编译) 正如你的错误告诉你的 C++标准禁止const元素容器,因为分配器[const t>格式不正确。< /p> 一种可能的解决方案是使用: std::vector>lc; 这将保证您的示例同时适用于libstdc++和libc++。或者,在这种特殊情况下也可以使用 这里有一个你认为decltype(c.begin()->first)的类型是什么,为什么

问题是
decltype(c.begin()->first)
返回一个
const int
(当使用libstdc++时-您的示例使用libc++编译)

正如你的错误告诉你的

C++标准禁止const元素容器,因为分配器[const t>格式不正确。< /p> 一种可能的解决方案是使用:

std::vector>lc;
这将保证您的示例同时适用于libstdc++libc++。或者,在这种特殊情况下也可以使用


这里有一个

你认为
decltype(c.begin()->first)
的类型是什么,为什么?如果你知道
T
总是有一个
key\u-type
成员,那么使用
typename T::key\u-type
而不是
decltype(…)
,可能更简单,像
std::map
std::unordered\u map
。键不是必须是
const
?我想知道为什么
libc++
没有问题。在某种程度上,人们应该使用
key\u-type
typedef来代替这种复杂的混乱@用户207933它总是
const int
。只是libc++的实现方式恰好是
vector
不那么容易爆炸。
decay\u t
而不是
remove\u const\u t
,因为您的目标是获得适合存储的类型,
decay\u t
正是这样做的吗?
#include "stdafx.h"
#include <iostream>

#include <vector>
#include <map>

template <typename T>
auto Copy(T c)
{
    std::vector<decltype(c.begin()->first)> lc;

   //Copying

    return lc;

}

int main()
{
    std::map<int, int> map;

    Copy(map);


    return 0;
}
"The C++ Standard forbids containers of const elements allocator<const T> is ill-formed." 
std::vector<std::decay_t<decltype(c.begin()->first)>> lc;