参考链接:
https://blog.csdn.net/Yshe_xun/article/details/7315135?utm_source=distribute.pc_relevant.none-task
https://blog.csdn.net/lixiaogang_theanswer/article/details/88350726
返回值 decltype(表达式)
解释:返回值的类型是表达式参数的类型
示例1:常用数据类型
int i = 0;
float j = 1.0;
double k = 2.0;
decltype(i) m = 6.0;
decltype(i+k) n = 5.2;
std::cout<<typeid(m).name()<<std::endl; //打印结果: i(表示变量n是int类型)
std::cout<<typeid(n).name()<<std::endl; //打印结果: d(表示变量n是double类型)
注意:C++的RTTI机制会为每一个类型都产生一个type_info 类型的数据,因此可使用 typeid 随时查询某变量的数据类型。typeid会返回该变量相应的type_info数据,而该type_info中有一个成员函数 name 可以返回该变量的名字。相当于2个过程。即
typeid(变量名)–>① type_info ->② name成员函数 =>得到变量类型:
示例2:STL
vector<int> _v{1,2,3,4,5,6,7,8,9,10};
typedef decltype(_v.begin()) iter;
std::cout<<typeid(iter).name()<<std::endl; //输出:N9__gnu_cxx17__normal_iteratorIPiSt6vectorIiSaIiEEEE
for(iter it = _v.begin(); it != _v.end(); ++it)
{
std::cout<<*it<<" ";
}
//输出: 1 2 3 4 5 6 7 8 9 10
vector<int> v1{1,2,3},v2{4,5,6},v3{7,8,9};
map<int, vector<int>> m{{1, v1},{2, v2},{3, v3}};
std::cout<<"size:"<<m.size()<<std::endl;
typedef decltype(m.begin()) iter;
typedef decltype(v1.begin()) _iter;
std::cout<<typeid(iter).name()<<std::endl;
std::cout<<typeid(_iter).name()<<std::endl;
for(iter it = m.begin(); it != m.end(); ++it)
{
std::cout<<it->first<<std::endl;
vector<int> &tempList = it->second;
for(_iter _it = tempList.begin(); _it != tempList.end(); ++_it)
{
std::cout<<*_it<<" ";
}
std::cout<<std::endl;
}
输出:
St17_Rb_tree_iteratorISt4pairIKiSt6vectorIiSaIiEEEE
N9__gnu_cxx17__normal_iteratorIPiSt6vectorIiSaIiEEEE
1
1 2 3
2
4 5 6
3
7 8 9